The jQuery Parent method (.parent()) returns the direct parent of the selected element.
$(selector).parent(filter)
filter is an optional parameter. When used, it narrows down the direct parent search.
<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).
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.
The important links of this tutorial are given below:
Share this article -