jQuery Traversing: Descendants
To go down the tree and get the elements inside another element, jQuery has two main methods: children() and find().
<div id="menu">
<ul class="main">
<li class="item">Home
<ul class="sub">
<li class="item">Team</li>
<li class="item">History</li>
</ul>
</li>
<li class="item">Contact</li>
</ul>
</div>
| Method | Returns |
|---|---|
.children() | Only the direct children (one level down) |
.find(sel) | All descendants which match the selector (any level) |
.contents() | All child nodes including text nodes and comments |
console.log($('#menu').children().length);
console.log($('#menu').children().attr('class'));
console.log($('#menu').find('li').length);
console.log($('#menu').find('.sub li').length);
console.log($('.main').children('li').length);
Console output
1
main
4
2
2
children()found only the oneul.main, because it is the only direct child.find('li')found all 4 list items, on every level.
find() needs a selector
You must give a selector to find(). To get all descendants, use find('*').
console.log($('#menu').find('*').length);
Console output
6
children() with a filter
console.log($('.main').children('.item').length);
console.log($('.main').children('.item').first().contents().first().text().trim());
Console output
2
Home
Example: find inside a clicked element
<table id="t">
<tr><td class="name">Ravi</td><td class="city">Pune</td></tr>
<tr><td class="name">Maya</td><td class="city">Delhi</td></tr>
</table>
$('#t tr').on('click', function () {
var name = $(this).find('.name').text();
var city = $(this).find('.city').text();
console.log(name + ' lives in ' + city);
});
$('#t tr').eq(1).click();
Console output
Maya lives in Delhi
Scoped selector as a shortcut
The second argument of $() is the context. $('.name', this) is the same as $(this).find('.name'), but the find() way is easier to read.
Note:
Use children() when you know the structure and need only the first level. It is faster than find(). Next: Traversing: Siblings.
Congratulations! Chapter Finished. Learn more about the similar topics:
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |