jQuery Traversing Ancestors: parent() and parentsUntil() Functions
What are ancestors in jQuery Traversing
You may use jQuery to find an element's ancestors by traversing up the DOM tree.
A parent, grandparent, great-grandparent, and so on are all examples of ancestors.
Traversing Up the DOM Tree
The following are three important jQuery techniques for navigating the DOM tree:
-
parent()
-
parents()
-
parentsUntil()
jQuery parent() Method
The parent()
function returns the direct parent element of the specified element and is returned by the parent()
function.
This approach traverses only one level of the DOM tree.
The direct parent element of each element is returned in the following example:
Example of parent method in jQuery ancestors
$(document).ready(function(){
$("span").parent();
});
jQuery parents() Method
The parents return all ancestor elements of the specified component () method, all the way up to the document's root element (html>).
All ancestors of all elements are returned in the following example:
Example of parents method in jQuery
$(document).ready(function(){
$("span").parents();
});
An extra argument can be used to filter the ancestor search.
All ancestors of all elements that are
- elements are returned in the following example:
Example
$(document).ready(function(){
$("span").parents("ul");
});
jQuery parentsUntil() Method
All ancestor elements between two provided inputs are returned by the parentsUntil()
function.
Between a and a
element, the following example returns all ancestor elements:
Example of parentsUntil method
$(document).ready(function(){
$("span").parentsUntil("div");
});