夏期劇場
夏期劇場

Reputation: 18327

jQuery Selector nth-child(n) under unknown level?

For the 2nd <h3>World!</h3> in this sample scenario (Please note <..> elements are unknown elements at all levels):

<div></div>
<div class="class1">
    <..>
        <h3>Hello!</h3>
        <..>
            <h3>World!</h3>
        </..>
    </..>
</div>

Lets assume we know only:

So I want to use nth-child(n) selector. But I can't use like this:

$("div.class1 h3:nth-child(2)").html();

Now i'm realized is the nth-child(n) selector can select only the Direct Child of the parent element, rite?

Can i make it work by using nth-child(n) selector?

Upvotes: 1

Views: 1959

Answers (4)

charlietfl
charlietfl

Reputation: 171669

Find all elements within class containing h3, isolate last of each

DEMO: (nested version) http://jsfiddle.net/3daHU/1/

$("div.class1 *:has(h3)").each(function(){   
    $(this).children('h3:last').css('color','red')
})

Upvotes: 0

Jezen Thomas
Jezen Thomas

Reputation: 13800

I think you're looking for .eq().

$('h3').eq(1).html();

In this example, jQuery returns an array of h3 elements, and you're selecting the second item in the array.

Upvotes: 1

Esailija
Esailija

Reputation: 140230

$("div.class1 h3:eq(1)").html();

Select all h3's under div.class1 depth first, and then take the second one.

Upvotes: 4

jaypeagi
jaypeagi

Reputation: 3141

$("div.class1 h3") will give you an array of the two h3. SO you could use $("div.class1 h3")[1] to get the second matching element.

Upvotes: 0

Related Questions