Javatpoint Logo
Javatpoint Logo

jQuery parent() method

The parent() method in jQuery finds the direct parent of the given selector. It is an inbuilt function in jQuery. This method only traverses a single level up in the DOM tree and returns the direct parent of the selected element.

The parent() method is similar to the parents() 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.

Example1

In this example, we are not using the optional parameter of the parent() method. Here, there is a div element that contains a ul element, a heading h2, and a paragraph element.

We are applying the parent() method for searching the parent of the heading h2. If we use the parents() method instead of using the parent() method, all ancestors of the heading h2, including the body element, will be highlighted.

Test it Now

Output:

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

jQuery parent() method

After clicking the given button, the output will be -

jQuery parent() method

Example2

In this example we are using the optional parameter of the parent() method to find the parent of the first paragraph element. Here, there are more than one paragraph elements but we have to find the parent of the first paragraph element. So, we are passing the pseudo-selector (:first) as the optional value of the parent() method.

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

jQuery parent() method

After clicking the given button, the output will be -

jQuery parent() method

Example3

In this example we are using the optional parameter of the parent() method for finding the specific parent of the given selector. Here, there are three paragraph elements with different parents. We are finding the h2 parent of the paragraph element. So, to achieve the same we have to pass the h2 as the optional value of the parent() method.

Test it Now

Output:

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

jQuery parent() method

After clicking the given button, the output will be -

jQuery parent() method




Youtube For Videos Join Our Youtube Channel: Join Now

Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA