Traversing Down the DOM Tree
Explore different jQuery methods such as children() and find(), usedfor traversing down the DOM tree.
We'll cover the following
In this lesson, we will explore different methods in jQuery that allow the user to traverse down the DOM tree. Given the initial selection, these methods enable the user to query both children and descendant elements.
The children and descendant traversal methods, along with relevant examples, are given below.
children()
method
The children()
method returns all the immediate child elements of a given element. This method traverses just one step down the DOM tree to return the child elements.
Consider a web page with the above DOM tree. In the web page, the div
element has two child elements: p
and span
, and another grandchild span
. In the jQuery code below, we assign a click
event handler to the div
element. In the event handler function, line 3, we access the child elements (p
and span
) of the given div
element using the children()
method, also shown in the illustration above. Then, we change the border color of both the child elements to red in line 4.
Run the code below. In the web page output, click on the
div
element. Observe how the border color of the child elements (p
andspan
) changes to red.
Filtering child elements
The children()
method takes an optional selector parameter to filter out the child elements. For example, in the code above, if we replace $("div").children()
with $("div").children("p")
, then it only returns the paragraph child elements.
Run the code below. In the web page output, click on the
div
element. Now observe that the border color of only thep
child element changes to red.
find()
method
The find()
method receives a selector as an argument. The method traverses all the way down the DOM tree and returns all the descendant elements of a chosen element that match against the specified selector.
Imaging a web page with the DOM tree shown above. In the web page, the div
element has two child elements: p
and span
. The p
element itself has a child element span
. In the jQuery code below, we assign a click
event handler to the div
element. In the event handler function, line 3, we access all the span
descendant elements of the given div
element using the find("span")
method, also shown in the illustration above. Then we change the border color of all the span
descendant elements to red in line 4.
Run the code below. In the web page output, click on the
div
element. Observe that the border color of all thespan
descendant elements changes to red.
Finding all descendants
The find()
method also allows us to find all the descendants of a given element. For this purpose, we pass "*"
as the selector argument.
Run the code below. In the web page output, click on the
div
element. Now, observe that the border color of all the descendant elements changes to red usingfind("*")
.