We have already discussed the basics of traversing. Next we'll discuss the methods that you can get from jQuery library to retrieve information about elements' parents and ancestors. This tutorial introduces usage and definitions of the following functions: jQuery .parent(), .parents(), and .parentsUntil().
You will learn how to add selector expressions to these functions.
Contents
jQuery Parent: Main Tips
- In jQuery, traversing refers to moving through the DOM tree to access certain HTML elements.
- By using jQuery, you can traverse upwards the DOM tree.
- There are three main methods used to retrieve parents or other ancestors.
Traversing Ancestors
When traversing upwards, jQuery provides these methods:
.parent()
: return direct parent and traverse one level up the DOM tree..parents()
: return all ancestors up to the root, can filter the search..parentsUntil()
: return all ancestors in between two specified elements.
.parent()
By using the jQuery .parent()
method, you can traverse one level up the DOM tree and return the direct parent of a specified element. It is also possible to add a selector expression ($()
). Then, the specified elements are filtered to find matches. The following syntax is used for this statement:
$(selector).parent([filter])
To see how we make jQuery get parent element, take a look at a code example of this method:
$("span").parent().css({
"color": "blue",
"border": "2px solid green"
});
.parents()
The jQuery .parents()
function returns all ancestors of the specified element up the root. Just like in the previous method, you can add a selector to find specific matches. We present the correct way of writing this statement for finding jQuery ancestors:
$(selector).parents([filter])
By entering the optional filter, you can filter the search for ancestors.
Now, take a look at this code example, showing the usage of jQuery .parents()
:
$("li").parents().css({
"color": "blue",
"border": "2px solid green"
});
.parentsUntil()
The jQuery .parentsUntil()
method returns all ancestors of the specified element up the root. You can add a selector for this function. If method traverses succesfully (finds a match), the jQuery object will be generated. It will consist of all ancestors up to the match (won't include the actual match). Here is the syntax for this statement:
$(selector).parentsUntil([selector],[filter])
Now, take a look at a code example of this method in use:
$("li").parentsUntil("div").css({
"color": "blue",
"border": "2px solid green"
});
jQuery Parent: Summary
- To make jQuery get parent elements, you will have to move through the DOM tree.
- There are three main functions, designed to retrieve parents and further ancestors:
.parent()
,.parents()
, and.parentsUntil()
.