tags:

views:

272

answers:

4
<div class="a" style="display:none">Content 1</div>
<div class="a" style="display:none">Content 2</div>

some other HTML...

<span id="b">foobar</span>

How can I match the first div class="a" above the span id="b" to show() it? The id="b" is the only thing I konow before.

+3  A: 
$("#b").closest(".a").show();

Try that.

inkedmn
maybe there is a div class a closer AFTER the span id b.
powtac
@inkedmn: Wrong. You're misunderstanding the `closest` method. http://api.jquery.com/closest/
SLaks
It looks like `closest` gives you the nearest ancestor of the current element. It appears that the OP needs the nearest sibling.
Aaron
+5  A: 

Like this:

$('#b').prevAll('.a:first').show();
SLaks
`prevAll` returns nodes in reverse order, so I write `:first` instead of `:last`. Note that this will only work if the two elements have the same direct parent.
SLaks
prevSiblings is not jQuery
powtac
Yes; I meant `prevAll`.
SLaks
This looked weird, so I tested it. Works nicely! jQuery becomes more amazing to me every day.
Aaron
The elements dont have the same parent :(
powtac
@powtac: Then you shouldn't suggest they do with your question's code.
Jonathan Sampson
A: 

Do the elements share an ancestor? If so, you may be able to combine inkedmn's and SLaks's answers:

$('#b').closest('parentType').prevAll('.a:first').show();

Or something similar, depending on your DOM.

Aaron
A: 

As long as I am understanding multiple selectors correctly, this should work. It will get all divs with class 'a' and and the span with the id of 'b'. They will be "in document order" according to the documentation. Then you'll need to get the div prior to your span tag and display it.

var elems = $('span#b, div.a');
var divIndex;
for (var i = 0; i < elems.length; i++)
{
    if (elems[i].tagName == "SPAN")
    {
        divIndex = i - 1;
        break;
    }
}

$(elems[divIndex]).show();
rosscj2533