jQuery parents() method

The parents() method in jQuery is used to get all ancestor elements of the given selector. It is an inbuilt function in jQuery. This method traverses upwards from the parent element, all the level up in the DOM tree and returns all ancestors of the selected element.

The parents() method is similar to the parent() method, as both travel up to the DOM tree and return the parent element. But the difference is that the parents() method traverses multiple levels up in the DOM tree and returns all ancestors, including a grandparent, great-grandparent, etc. of the given selector, while the parent() method traverses a single level up and only returns the direct parent of the given selector.

Syntax

The selector in the above syntax represents the selected element whose parent is to be searched.

The filter in the above syntax is the optional parameter that specifies the selector expression, which is used to narrow down the search for ancestors. If we need to get multiple ancestors, we have to separate each expression with a comma.

Example1

In this example, we are not using the optional parameter of the parents() method. Here, there is a div element that contains a ul element, a heading h4, and a paragraph element. We are applying the parents() method for searching the ancestors of the heading h4. In the output, we will get all ancestors of the heading h4, including the body element.

If we use the parent() method instead of using the parents() method, the direct parent of the heading h2 will be highlighted.

Test it Now

Output

After the execution of the above code, the output will be -

jQuery parents() method

After clicking the given button, the output will be -

jQuery parents() method

Example2

In this example, we are using the optional parameter of the parents() method to find the ul ancestor of the paragraph element. So, we are passing the ul as the optional value of the parents() method.

Test it Now

Output

After the execution of the above code, the output will be -

jQuery parents() method

After clicking the given button, the output will be -

jQuery parents() method

Example3

In this example, we are using the parents() method to get the multiple ancestors of the paragraph element. We are using the optional parameter of the parents() method to only get the ul and h4 parents of the paragraph element among all ancestors.

Test it Now

Output

jQuery parents() method

After clicking the given button, the output will be -

jQuery parents() method




Latest Courses