How to use jQuery Parents Method – .parents() for DOM Traversal

How to use jQuery Parents Method – .parents() for DOM Traversal

The jQuery Parents Method (.parents() returns all the parents (ancestor elements) of the selected elements. This goes all the way to the DOM root (body, html).

Syntax of jQuery Parents

$(selector).parents(filter)

filter is an optional parameter that is used for narrowing down the search for parents.

Related: There is also jQuery Parent method (not parents) which does the same thing but in a different manner.

Example 1: jQuery Parents

<html>
<body>
  <div id="div1">
    <span class="spanCss">Span</span>
  </div>
</body>
 
<button id="button1">Click</button>
$("#button1").click(function () {
    $(".spanCss").parents().css({ "color": "red", "border": "2px solid red"});
});

In the above code when the button is clicked you will see 3 red borders around the div1, body and html as these are the 3 parents of the .spanCss element.

jquery parents example

Example 2: jQuery Parents filter parameter

In the below code I will apply red border on the p element only. I will do it by passing it’s class (which is .first) as the filter parameter.

<div id="div2">
    <p class="first">
        <span class="mySpan">Span</span>
    </p>
</div>
 
<button id="button2">Click</button>
 
$("#button2").click(function () {
    $(".mySpan").parents(".first").css({ "color": "red", "border": "2px solid red" });
});

If I want to apply the red border on the body only, then I have to pass body for the filter parameter.

$(".mySpan").parents("body").css({ "color": "red", "border": "2px solid red" });
Also to read: How to work with jQuery Children Method

Using multiple element for the filter parameter

I can also provide multiple elements for the filter parameter, this can be done by separating them with commas.

The below code will add the red border for the .first element and the body.

$(".mySpan").parents(".first, body").css({ "color": "red", "border": "2px solid red" });

Check the download link:

DOWNLOAD

SHARE THIS ARTICLE

  • linkedin
  • reddit
yogihosting

ABOUT THE AUTHOR

I hope you enjoyed reading this tutorial. If it helped you then consider buying a cup of coffee for me. This will help me in writing more such good tutorials for the readers. Thank you. Buy Me A Coffee donate