views:

19

answers:

2

i have the following html:

<span class="addEventHidden"><img src="/Content/Images/add.gif"></span>
 <br>
 <div class="event">My Event</div>
 <div  class="event">My Event 2</div>
 <div  class="event">My Event 3</div>
 <div  class="event">My Event 4</div>

i then have the following event handler when i click on any "event" div:

$('.event').live('click', function () {

i now want to get a reference to the object with the class="addEventHidden" from this event handler. i tried this:

  var previousAddEvent = $(this).prev(".addEventHidden");

but that didn't seem to work. Any suggestions?

+3  A: 

Use .prevAll() and :first, like this:

var previousAddEvent = $(this).prevAll(".addEventHidden:first");

.prev("selector") gets the immediately previous sibling if it matches the selector, it doesn't look until it finds a match. .prevAll() will get all previous sibling, in the expected order (reverse) so we just want the first one it came across matching our selector.

Nick Craver
@Nick Craver - once again, your answers on jquery are as good as gold
ooo
A: 

Not knowing anything more about your HTML, I'm going to assume you've containerized this and other objects like it appropriately. If you have, one answer is

var previousAddEvent = $('.addEventHidden', $(this).parent());
Elf Sternberg