THE WORLD'S LARGEST WEB DEVELOPER SITE
HTMLCSSJAVASCRIPTSQLPHPBOOTSTRAPJQUERYANGULARXML
 

jQuery Traversing - Ancestors

Ancestors are father, grandfather, or great-grandfather, and so on.

With jQuery, you can traverse up the DOM tree to find the ancestor of an element.


Walk up the DOM tree

These jQuery methods are useful for traversing the DOM tree up:

  • parent ()
  • parents ()
  • parentsUntil ()

jQuery parent () method

parent () method returns the immediate parent of the selected element.

This method only traverses the DOM tree one level up.

The following example returns each <span> Element's immediate parent:

Example

$(document).ready(function(){
    $("span").parent();
});
Try it yourself »

jQuery parents () method

parents () method returns all ancestor elements of the selected element, it goes all the way up to the root element of the document(<html>).

The following example returns all <span> All ancestors of the element:

Example

$(document).ready(function(){
    $("span").parents();
});
Try it yourself »

You can also use optional parameters to filter searches for ancestor elements.

The following example returns all <span> All ancestors of the element and it is <ul> element:

Example

$(document).ready(function(){
    $("span").parents("ul");
});
Try it yourself »

jQuery parentsUntil() Method

The parentsUntil () method returns all ancestor elements between two given elements.

The following example returns between <span> 与 <div> All ancestor elements between elements:

Example

$(document).ready(function(){
    $("span").parentsUntil("div");
});
Try it yourself »

jQuery Traversing Reference

For a total diagram of all jQuery Traversing techniques, if it's not too much trouble go to our jQuery Traversing Reference.