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

powtac
  • 40,542
  • 28
  • 115
  • 170

4 Answers4

8

Like this:

$('#b').prevAll('.a:first').show();
SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • 1
    `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 Feb 24 '10 at 17:40
  • This looked weird, so I tested it. Works nicely! jQuery becomes more amazing to me every day. – Aaron Feb 24 '10 at 17:44
  • The elements dont have the same parent :( – powtac Feb 24 '10 at 17:44
  • 1
    @powtac: Then you shouldn't suggest they do with your question's code. – Sampson Feb 25 '10 at 18:49
3
$("#b").closest(".a").show();

Try that.

brettkelly
  • 27,655
  • 8
  • 56
  • 72
  • maybe there is a div class a closer AFTER the span id b. – powtac Feb 24 '10 at 17:36
  • 2
    @inkedmn: Wrong. You're misunderstanding the `closest` method. http://api.jquery.com/closest/ – SLaks Feb 24 '10 at 17:36
  • 2
    It looks like `closest` gives you the nearest ancestor of the current element. It appears that the OP needs the nearest sibling. – Aaron Feb 24 '10 at 17:38
0

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
  • 6,988
  • 4
  • 31
  • 48
0

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
  • 9,195
  • 7
  • 39
  • 56