Russel Riehle
Russel Riehle

Reputation: 267

How can I access descendants using jQuery?

I have only one ID (main).

I'm trying to set .css() to "main[0]->sub[0]->left[0]" as you can see below:

<div id="main">

    <div class="sub">
        <div class="left">
            <div class="subsub">
                main[0]->sub[0]->left[0]
            </div>
            <div class="subsub">
                main[0]->sub[0]->left[1]
            </div>
        </div>
        <div class="right">
            main[0]->sub[1]
        </div>
    </div>

    <div class="sub">
        <div class="left">
            <div class="subsub">
                main[1]->sub[0]->left[0]
            </div>
            <div class="subsub">
                main[1]->sub[0]->left[1]
            </div>
        </div>
        <div class="right">
            main[1]->sub[1]
        </div>
    </div>

</div>

I can access the first MAIN child this way:

$($('#main').children()[0]).css('MY CSS...');

And the second MAIN child this way:

$($('#main').children()[1]).css('MY CSS...');

But how can I access "sub" class children?

Upvotes: 0

Views: 53

Answers (3)

Nic
Nic

Reputation: 13733

Here's a sizzle selector that could find the first child of both:

$('#main .sub .left :first-child').css('color', 'red');

That's not the most efficient (or only selector), as $('.subsub:first-child').css() would work as well. Depending on how many times you're doing this, it could be more efficient to cache the parent and use .children() per this answer.

Upvotes: 1

Vanquished Wombat
Vanquished Wombat

Reputation: 9525

Use a combination of .find and :first selectors.

$('#main').find(".subsub:first")

Upvotes: 1

willwolfram18
willwolfram18

Reputation: 1887

Every jQuery element has the $.children() method. So you can do $($($('#main').children()[0]).children[0]).css()

However, if it's the same set of CSS rules being applied to the elements you can do $("#main .left .subsub").css()

Upvotes: 1

Related Questions