.parents()
methodThe .parents()
method in jQuery is used to get the ancestors of each element in the set of matched elements, optionally filtered by the selector, DOM node, or jQuery object passed.
.parents()
method Syntax.parents(selector)
.parents()
method ExampleFind all parent elements of the item with an id "python".
HTML
<ul> <li class="category">Language <ul> <li class="lang">Java <ul> <li>Java tutorial</li> <li>Java Examples</li> </ul> </li> <li class="lang">Python <ul id="python"> <li>Python tutorial</li> <li id="pyex">Python Examples</li> </ul> </li> </ul> </li> <li class="category">Tools</li> <li class="category">Lautturi</li> </ul>
jQuery
var parentElems = $( "#python" ).parents() .map(function(){ return this.tagName; }) .get() .join(", "); $('#log').html("The `#python` element's parents are:"+ parentElems);
Result
The `#python` element's parents are:LI, UL, LI, UL, BODY, HTML
Finds the parents element with a class lang
for the element with an id pyex
.
$( "#pyex" ).parents('.lang').css( "border", "1px solid red" );