Russel Riehle Russel Riehle - 27 days ago 10
jQuery Question

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?

Answer

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()