jQuery Traversal - Ancestors
- Previous Page jQuery Traversal
- Next Page jQuery Descendants
Ancestors are parents, grandparents, or great-grandparents, etc.
With jQuery, you can traverse up the DOM tree to find ancestors of elements.
Traverse Up the DOM Tree
These jQuery methods are very useful as they are used to traverse up the DOM tree:
- parent()
- parents()
- parentsUntil()
jQuery parent() Method
The parent() method returns the direct parent element of the selected element.
This method only traverses the DOM tree one level up.
The following example returns the direct parent element of each <span> element:
Example
$(document).ready(function(){ $("span").parent(); });
jQuery parents() Method
The parents() method returns all ancestor elements of the selected elements, going up to the root element of the document (<html>).
The following example returns all ancestors of all <span> elements:
Example
$(document).ready(function(){ $("span").parents(); });
You can also use optional parameters to filter the search for ancestor elements.
The following example returns all ancestors of all <span> elements, and it is the <ul> element:
Example
$(document).ready(function(){ $("span").parents("ul"); });
jQuery parentsUntil() Method
The parentsUntil() method returns all ancestor elements between the two given elements.
The following example returns all ancestor elements between the <span> and <div> elements:
Example
$(document).ready(function(){ $("span").parentsUntil("div"); });
jQuery Traversal Reference Manual
For a complete list of jQuery traversal methods, please visit our jQuery Traversal Reference Manual.
- Previous Page jQuery Traversal
- Next Page jQuery Descendants