Traversing Up the DOM Tree with jQuery
This article discusses useful jQuery methods for traversing up the DOM tree.
Traversing Up the DOM Tree
Lets refer the following html structure :
<div class="block">div
<p class="block">p
<span class="block">Hello</span>
</p>
</div>
In the above code “div” element is immediate parent of “p” which in turn is immediate parent of “span”

jQuery methods for traversing up the DOM tree
Following methods are helpful for traversing up the DOM tree :
•parent()
•parents()
•parentsUntil()
The parent() method
The parent() method provided in jQuery finds the immediate parent of the target element.
Example :
$("span").parent
<!DOCTYPE html> <html> <head> <style> .block { display: block; border: 2px solid black; padding: 10px; color:black; } </style> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script> <script> $(document).ready(function() { //Change element background $("span").css("background", "green"); //Change parent's background $("span").parent().css( "background", "yellow"); $("span").parent().parent().css("background", "red"); }); </script> </head> <body> <div class="block">div <p class="block">p <span class="block">Hello</span> </p> </div> </body> </html>
The parents() method
The .parents() method allows us to search through the ancestors of these elements in the DOM tree.
.parents() is similar to .parent(), except that the .parent() only travels a single level up the DOM tree.
Example :
$("span").parents
<!DOCTYPE html> <html> <head> <style> .block { display: block; border: 2px solid black; padding: 10px; color:black; } </style> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script> <script> $(document).ready(function() { var parentEls = $("span").parents() .map(function() { return this.tagName; }) .get() .join(", "); $( "span" ).append( "<strong>" + parentEls + "</strong>" ); }); </script> </head> <body> <div class="block">div <p class="block">p <span class="block">span's parents are : </span> </p> </div> </body> </html>
The parentsUntil( ) Method
The parentsUntil() method behaves in a similar way as the parents() method, except that it prevents the search from ascending the tree farther than specified element.
The traversal stops immediately before the match.
Example :
$("span").parentsUntil()
<!DOCTYPE html> <html> <head> <style> .block { display: block; border: 2px solid black; padding: 10px; color:black; } </style> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script> <script> $(document).ready(function() { $("span").parentsUntil("div").css( "background", "yellow"); }); </script> </head> <body> <div class="block">div <p class="block">p <span class="block">span</span> </p> </div> </body> </html>
© 2016, https:. All rights reserved. On republishing this post, you must provide link to original post