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


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

Example 1: jQuery Parents

  <div id="div1">
    <span class="spanCss">Span</span>

<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 its class (which is .first) as the filter parameter.

<div id="div2">
    <p class="first">
        <span class="mySpan">Span</span>

<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 pass body for the filter parameter.

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


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 red border for the .first element and the body.

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


Share this article -



This article has been written by the Technical Staff of YogiHosting. Check out other articles on "WordPress, SEO, jQuery, HTML" and more.