Using jQuery you can easily traverse up the DOM tree to find ancestors of an element. An ancestor is a parent, grand-parent and so on.
Traversing Up the DOM Tree:
Logically ancestor is a parent, grandparent, great-grandparent, and so on. jQuery provides useful methods to traverse up in the DOM tree to easily get the parent or other ancestors of an element in the hierarchy.
Following are the jQuery methods that are used to traverse up the DOM tree:
parent()
parents()
parentsUntil()
jQuery parent() Method:
The parent() method in jQuery is used to get the direct parent of the selected element.
This method only travels a single level up the DOM tree.
The following example will highlight the direct parent element of the <li> which is <ul> by adding the class .highlight-parent on document ready.
The parents() method is used to get the ancestors of the selected element. This method traverses upwards from the parent element along with ancestors of DOM elements, all the way up to the document’s root element (<html>).
In the example given below, the border will be added around the ancestor elements of the <li> which are <ul>, <div>, <body> and the <html> elements.
If you want you can optionally include one or more selector as a parameter within the parents() method to filter your search for the ancestors. In the following example, the border will be applied around the ancestors of the <il> that is to the <div> element.
The parentsUntil() method of jQuery returns all ancestor elements between two given arguments.
In the following example, a border will be added to all the ancestor elements of the <li> excluding <html> element. The border will be added to the <ul>, <div> and <body> element.
We use cookies to ensure that we give you the best experience on our website. If you continue to use this site we will assume that you are happy with it.Ok