<h2 id="h2a"></h2>
<h3 id="h3a"></h3>
<h3 id="h3b"></h3>
<h2 id="h2b"></h2>

$('#h2b').prev();
returns [h3#h3b] // returns previous sibling

$('#h2b').prev('h3');
returns [h3#h3b] // returns previous sibling because it is an h3

$('#h2b').prev('.foo');
returns [] // empty, because previous sibling does have class of 'foo'

$('h2').prev('h3');
returns [h3#h3b]

$('h2,h3').prev('h3');
returns [h3#h3a,h3#h3b]

What you're asking for is a little more complex than you think. I haven't
tested out this code, but hopefully it will get you pointed in the right
direction. Essentially, you need to find the index of the h2 you want.

var prevIndex = $('h2').index( $('#h2b')[0] ) - 1;
$('h2:eq('+prevIndex+')');

This should work... but it is a little wasteful as it performs the same
search on h2s over and over again. Another way (that I'm not sure will work)
is:

var h2cache = $('h2');
var prevIndex = h2cache.index( $('#h2b')[0] ) - 1;
h2cache.filter(':eq('+prevIndex+')');

I'm not sure if there is an easier way... but I'm sure someone will correct
me if there is :)

Good luck,
Brian.


On 8/6/07, DaveG <[EMAIL PROTECTED]> wrote:
>
>
>
>
>
> On Mon, 6 Aug 2007 08:14:28 -0700, "Glen Lipka" <[EMAIL PROTECTED]> wrote:
> > It would help if you put up a skeleton page somewhere to demonstrate the
> > challenge.
> > :)
> Good point. Unfortunately, I can't do that right now, but here's a
> skeleton of the issue:
>
> <h2 id="h2a" class="h2">Heading 2a</h2>
>    <h3 id="h3a" class="h3">Heading 3a</h3>
>    <h3 id="h3b" class="h3">Heading 3b</h3>
> <h2 id="h2b" class="h2">Heading 2b</h2>
>
>
> In this case, I'd like to be able to do the following:
>    1] From #h2b, get the previous level 2 header (should return "#h2a").
> Note, this does not work: ('#h2b').prev('.h2')
>    2] From #h2b, get the previous level 3 header. (should return "#h3b").
>    3] From #h2b, get the first level 3 header from the previous level 2
> header (should return "#h3a").
>
>
> Note, that this is a 'clean' sample. The real scenario has plenty of other
> DOM objects between header levels.
>
>
> ~ ~ Dave
>
>

Reply via email to