jQuery Parent Method – .parent() complete usage guide with codes

jQuery Parent Method – .parent() complete usage guide with codes

The jQuery Parent method (.parent()) returns the direct parent of the selected element.

Syntax of jQuery Parent Method

$(selector).parent(filter)

filter is an optional parameter. When used, it narrows down the direct parent search.

Just like .parent() method, jQuery children method is used to select children of elements based on certain conditions.

Example 1: jQuery Parent

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

<button id="button1">Click</button>

$("#button1").click(function () {
    $(".spanCss").parent().css({ "color": "red", "border": "2px solid red" });
});

The above button click, will add a red border around the 2 p elements because they are the direct parents of the elements (2 span elements).

jquery parent example

There is also jQuery Parents method (note extra ‘s’) which does the same thing but in a slightly different way.

Example 2: jQuery Parent with filter parameter

In this jQuery Parent example I will use the filter parameter. See the below code:

<div id="div2">
    <p class="first">
        <span class="mySpan">Span of parent with class 'first'</span>
    </p>
    <p class="second">
        <span class="mySpan">Span of parent with class 'second'</span>
    </p>
</div>

<button id="button2">Click</button>
$("#button2").click(function () {
    $(".mySpan").parent(".first").css({ "color": "red", "border": "2px solid red" });
});

Here I have added – .first as the filter parameter and this will just add the red border around the first p element, as it is having the .first CSS class.

jquery parent with filter

The important links of this tutorial are given below:

DEMO DOWNLOAD

Share this article -

yogihosting

ABOUT THE AUTHOR

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