Traversing Up the DOM Tree
Explore different jQuery methods such as parent(), parents(), and parentsUntil() built for traversing up the DOM tree.
We'll cover the following
In this lesson, we will explore different jQuery methods that allow the user to traverse up the DOM tree. Given the initial selection, these methods enable the user to query both parent and ancestor elements.
The parent and ancestor traversal methods, along with relevant examples, are given below.
parent()
method
The parent()
method returns the immediate parent element of a given element. The method traverses one step up the DOM tree to return the parent element.
Consider a web page with the DOM tree shown above. In the webpage, p
is the parent and div
is the grandparent of the nested span
element. In the jQuery code below, we assign a click
event handler to the span
element. In the event handler function, line 3, we access the parent element (p
) of the given span
element using the parent()
method, also shown in the illustration above. Then, we change the border color of that parent element to red in line 4 using the css()
method.
Run the code below. In the web page output, click on the
span
element. Observe the border color of the parent element (p
) change to red.
parents()
method
The parents()
method returns all the ancestor elements of a given element. The method traverses all the way up the DOM tree to return all the ancestor elements.
Consider a web page with the above DOM tree. In this web page, we can use the parents()
method to get all the ancestors of the span
element. In the event handler function, line 3, we access the ancestor elements of the given span
element using the parents()
method, also shown in the illustration above. Then, we change the border color of all the ancestor elements to red in line 4.
Run the code below. In the web page output, again click on the
span
element. Observe how the border color of all the ancestor elements changes to red.
parentsUntil()
method
The parentsUntil()
method receives a selector as an argument which specifies where to stop matching the ancestor elements.
This method traverses all the way up the DOM tree until the specified ancestor is found. Then the method returns all the elements between the given element and the specified ancestor.
Consider a web page with the DOM tree shown above. In this web page, span
is the parent, p
is the grandparent, and div
is the great grandparent of the nested a
element. In the jQuery code below, we assign a click event handler to the a
element. In the event handler function, line 3, we access all the ancestor elements between the a
element and the div
element, using the parentsUntil("div")
method, also shown in the illustration above. Then we change the border color of all the ancestor elements between a
and div
to red in line 4.
Run the code below. In the web page output, click on the
a
element. Observe that the border color of all the ancestor elements betweena
anddiv
changes to red.