views:

321

answers:

2
<span>This is the span I want to select</span>
<div>something here</div>
<a id="start"></a>

Suppose can only access $('#start'),

I tried $('#start').prev('span') but not working.

+2  A: 
 $('#start')
    .parent()       // gets one up
    .find('span')   // gets the span element

same code using jsbin sandbox


Note:

you can't use prev() as it only gets the previous tag, and span, from the anchor tag is not the previous is the previous of the previous

from jQuery Documentation

Get a set of elements containing the unique previous siblings of each of the matched set of elements. Use an optional expression to filter the matched set. Only the immediately previous sibling is returned, not all previous siblings.

prev([filter])

the filter is to filter if the previous tag contains more than one, like:

<div>
   <span></span>
   <a></a>
</div>
<a id="a2"></a>

to get the span you use:

$('#a2').prev('span')
balexandre
why $('#start').prev('span') doesn't work?
Shore
added to the answer why you can't use it :)
balexandre
Check my answer, you'll get the very first span behind your element, so long as it's a sibling.
Anthony
for the html he exposed, I presented my solution :)
balexandre
Mine works with his HTML. I just added an extra span to show that it actually got the one he wanted. Cheers.
Anthony
A: 

Weird, it seems that prevAll goes backwards, starting at the first one right behind the starting element and working its way back. Makes sense, I suppose. Either way, the following worked for me:

//jquery :

$(document).ready(function(){
    $("#start").prevAll("span:first").css("font-weight", "bold");
  });

// html: 


<span>This is the span I don't want to select</span>
<span>This is the span I want to select</span>
<div>something here</div>
<a id="start">Stuff</a>
Anthony