27 Jan jQuery – Find Descendants of an element
A Descendant is a child, grandchild, and great grand-child of an element. Let us see the figure again:
In the above figure, the Descendant is <div>. The following are the key points about Ancestors from the above example:
- The <ul> and <ol> is the child of <div>
- The <span> element is the descendent of <div>
- The <li> is the child of the <ul> element
- The <li> is the child of the <ol> element
- The <strong> element is the descendent of <div>
Descendants suggest traversing down in the DOM tree and the following are the supported methods in jQuery:
- children()
- find()
Let us learn about each method one by one:
The children() method in jQuery
If you want to return the children of the selected element, use the jQuery children() method. Since it returns the direct children, therefore it traverses down. Let us see an example wherein we will return the children of the element <ul>:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script> <script> $(document).ready(function(){ $("ul").children().css({"color": "blue", "font-size": "24px","border": "4px solid red"}); }); </script> <style> .descendants * { display: block; border: 4px dashed black; color: black; font-size: 20px; padding: 10px; margin: 10px; } </style> </head> <body> <div class="descendants"> <div style="width:600px;">div --- great-grandparent --- <ul>ul --- grandparent --- <li>li --- parent --- <span>span</span> <span>span</span> </li> <li>li </li> </ul> </div> </div> </body> </html> |
Output
The find() method in jQuery
To return the descendant elements of the selected element, use the jQuery find() method. Let us see an example to return all <span> elements that are descendants of <div>:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script> <script> $(document).ready(function(){ $("div").find("span").css({"color": "blue", "font-size": "24px","border": "4px solid red"}); }); </script> <style> .ancestors * { display: block; border: 4px dashed black; color: black; font-size: 20px; padding: 10px; margin: 10px; } </style> </head> <body> <div class="ancestors"> <div style="width:600px;">div --- great-grandparent --- <ul>ul --- grandparent --- <li>li --- parent --- <span>span</span> <span>span</span> </li> <li>li </li> </ul> </div> </div> </body> </html> |
Output
No Comments