jQuery provides methods to move upward in the DOM tree and select ancestor elements of a selected node.
// Basic ancestor traversal syntax
$(selector).parent();
$(selector).parents();
$(selector).parentsUntil(selector);
// Traversing upward from the child element
$('#child').parent().css('border-color','red');
$('#child').parents().css('border-color','green');
$('#child').parentsUntil('.great-grandparent').css('border-color','blue');
// Selecting only ancestors with a specific class
$('#filtered-child').parents('.special').css('background','#ffecb3');
Type a jQuery command to see it in action on the live structure below (e.g., $('#target').parents()):
parent() affects only one level aboveparents() affects all ancestorsparentsUntil() stops before the matched selectorClick each button above to visually see how traversal flows upward in the DOM hierarchy.
parents() for performance.addClass() with traversal