jQuery parents method


jQuery parents method

jQuery parents method

The parents vs parent method

Unlike the jQuery .parent method, the .parents method traverses all levels up to find the “parents” of the specified element whereas .parent method travels just one level up.

See an example of parents method

To understand that, consider this structure:

<div>

<p>Child of div

<span>child of p and grandchild of div</span>

</p>

</div>

In that case, the div is a parent, p is a child of div while the span is the child of p and grandchild of the div element.

If you specify <span> element in jQuery parents method, it will travel through upper levels, to <p>, <div> to <HTML>.

How to use the jQuery $.parents method?

The syntax to use $.parents:

$(“child_element”).parents();

See the following section of $.parents method examples.

A parents method example

In this example, we used jQuery parents method and specified the span element, which is the grandchild of div1.

As you click the button “Run parents method” it will not only add CSS to <p> and <div> but also travels through HTML that adds CSS to other elements as well.

See demo by clicking the link below:

jQuery parents

Experience this example online



Using filter with parents jQuery method example

You can apply a filter to specify which parent level to go as using the $.parents method. In above example, as we did not specify any parent so the CSS was added across.

In this example, we will filter div1 and see the difference:

jQuery parents filter

Experience this example online



You can see, the CSS will be added to div1 only.

Useful reading: jQuery find | jQuery children



jQuery Guide