jQuery Traversing: Ancestors
Traversing means “moving through” the DOM. From one element you can find its parents, children and siblings. In this chapter we go up the tree to find the ancestors.
<div id="page" class="wrapper">
<ul id="menu" class="nav">
<li class="item"><span id="label">Home</span></li>
<li class="item">About</li>
</ul>
</div>
| Method | Returns |
|---|---|
.parent() | The direct parent only |
.parents() | All ancestors up to the html element |
.parentsUntil(sel) | All ancestors up to (but not including) the selector |
.closest(sel) | The closest ancestor (or the element itself) which matches the selector |
console.log($('#label').parent().prop('tagName'));
console.log($('#label').parents().map(function () { return this.tagName.toLowerCase(); }).get().join(' > '));
console.log($('#label').parentsUntil('#page').map(function () { return this.tagName.toLowerCase(); }).get().join(' > '));
console.log($('#label').closest('ul').attr('id'));
console.log($('#label').closest('.wrapper').attr('id'));
Console output
LI
li > ul > div > body > html
li > ul
menu
page
parents()goes upward, from the nearest parent to the html element.closest()is the most used. It looks at the element itself first, and then moves up.
Filter the ancestors
console.log($('#label').parents('ul').length);
console.log($('#label').parents('.wrapper').attr('id'));
Console output
1
page
closest() in event handlers
A very common job: a user clicks something small inside a bigger block, and you need the big block.
<div class="card" data-id="7">
<h3>Title</h3>
<button class="buy">Buy</button>
</div>
$('.buy').on('click', function () {
var id = $(this).closest('.card').data('id');
console.log('Buy card with id ' + id);
});
$('.buy').click();
Console output
Buy card with id 7
parent() vs closest()
| parent() | closest() |
|---|---|
| Only one level up | Goes up as many levels as needed |
| Always returns the direct parent | Returns the first match, or nothing |
| Good when the structure is fixed | Good when the structure can change |
Note:
Prefer closest() to a long chain like .parent().parent().parent(), because it still works if the HTML changes a little. Next: Traversing: Descendants.
Congratulations! Chapter Finished. Learn more about the similar topics:
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |