Question

<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.

Was it helpful?

Solution

 $('#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')

OTHER TIPS

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>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top