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).
$(selector).parents(filter)
filter is an optional parameter that is used for narrowing down the search for 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.
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" });
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: