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>
MethodReturns
.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 upGoes up as many levels as needed
Always returns the direct parentReturns the first match, or nothing
Good when the structure is fixedGood 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
Write jQuery code to count the items of a list
Write jQuery code to find the total of a table column
Write jQuery code to add alternate row colors to a table
Interview Questions & Answers
What are jQuery selectors?
What is the difference between find() and children() in jQuery?
What is the difference between parent(), parents() and closest() in jQuery?
How do you check if an element exists in jQuery?
What is the difference between this and $(this) in jQuery?
What is the use of end() in jQuery?