SyntaxStudy
Sign Up
jQuery jQuery Parent and Ancestor Traversal
jQuery Beginner 4 min read

jQuery Parent and Ancestor Traversal

Moving upward in the DOM tree — from a child to its parents and further ancestors — is one of the most common traversal patterns. It lets you find the containing element of a clicked item, validate an entire form from one input, or apply styles to a group from any element within it.

.parent()

.parent() moves exactly one level up to the immediate parent element. Optionally filter by a selector to return the parent only if it matches. If it doesn't match, an empty jQuery object is returned.

.parents()

.parents() travels all the way up to the document root, collecting every ancestor. The optional selector argument filters this collection. The results are ordered from nearest to farthest.

.closest()

.closest(selector) is like .parents(selector) but stops at the first match. Crucially, it also checks the element itself, so .closest('.card') matches whether the element is the card or is inside one.

  • .parent() — one level up
  • .parents('section') — all ancestor sections
  • .closest('.modal') — nearest modal ancestor (or self)
  • .offsetParent() — nearest positioned ancestor (for layout)
Example
// Delete button removes its card
$('.delete-btn').on('click', function () {
    $(this).closest('.card').fadeOut(300, function () {
        $(this).remove();
    });
});

// Highlight all ancestor sections of a focused input
$('input').on('focus', function () {
    $(this).parents('section').addClass('active-section');
}).on('blur', function () {
    $(this).parents('section').removeClass('active-section');
});

// One-level parent check
var $cell = $('td.selected');
if ($cell.parent('tr').hasClass('header-row')) {
    console.log('Selected cell is in header');
}
Pro Tip

.closest() is generally preferable to .parent() because it works regardless of how deeply nested the element is.