In this post we wil see when to use the parent ,Parents and ParentUntil method of Jquery traversing . These all three methods look like similar but their functionality are completely different.
parent()
>> It is used for selecting the parent element of given selector element.
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title></title> <script src="../../Scripts/jquery.min.js"></script> <style> .ancestors * { display: block; border: 1px solid; color: green; padding: 5px; margin: 15px; } </style> <script> $(function () { $("span").parent().css({ "color": "red", "border": "2px solid red" }); }); </script> </head> <body> <fieldset> <legend>This is the demo example of Parent method in Jquery</legend> <div class="ancestors"> <div style="width:500px;">Grand Parent of span <div style="width:400px;"> Parent of span <span>span</span> </div> </div> </div> </fieldset> </body> </html>
In the above example we saw that parent div of span has been only highlighted by red color.
parents()
>> It is used for selecting the all parents element of given selector
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title></title> <script src="../../Scripts/jquery.min.js"></script> <style> .ancestors * { display: block; border: 2px solid; color: green; padding: 5px; margin: 15px; } </style> <script> $(function () { $("span").parents().css({ "color": "red", "border": "2px solid red" }); }); </script> </head> <body> <fieldset> <legend>This is the demo example of Parents method in Jquery</legend> <div class="ancestors"> <div style="width:500px;">Grand Parent of Span <div style="width:400px;"> Parent of span <span>span</span> </div> </div> </div> </fieldset> </body> </html>
In the above example we saw that Parents method is used for selecting the all parents elements of given selector in DOM element.
ParentsUntil(Selector)
>> It is used for selecting the parents element of given selector on given condition.
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title></title> <script src="../../Scripts/jquery.min.js"></script> <style> .ancestors * { display: block; border: 2px solid lightgrey; color: lightgrey; padding: 5px; margin: 15px; } </style> <script> $(function () { $("p").parentsUntil("div").css({ "color": "red", "border": "2px solid green" }); }); </script> </head> <fieldset> <legend>This is the demo example of Parent method in Jquery</legend> <body class="ancestors"> body (great-great-grandparent) <div style="width: 500px;"> div (great-grandparent) <ul> ul (grandparent) <li>li (direct parent) <p>This is the paragraph</p> </li> </ul> </div> </body> </fieldset> </html>
In the above example we saw that parentuntil is used for selecting the DOM element from given selector element to given parent element.
One thought on “Parent,Parents and ParentUntil Method of Jquery Traversing (Part 13)”