In this post, we are going to discuss about an important jQuery traversing method to find all the descendents of an element. jQuery API provides find()
method to carry out this task.
jQuery find() method
The jQuery find() method returns all the descendant elements like child, grandchild and so on. This method is used if you want to search all the elements deeper in the DOM tree. This method traverses downwards and finds all its descendants of the selected element. This method takes a mandatory filtering parameter to narrow down the search.
Here is the general syntax for using find() method:
filter is the mandatory parameter passed to the find() method. filter could be any string selector expression, an element or a jQuery object.
jQuery find() example
Following example demonstrates the jQuery find() method usage.
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 40 |
<!doctype html> <html> <head> <title>jQuery Traversing find</title> <style> .highlight{ background: yellow; } div{ display: block; border: 3px solid black; color: black; padding: 5px; margin: 25px; width:250px; } span{ display: block; border: 3px solid green; color: black; padding: 5px; margin: 25px; width:200px; } </style> <script src="https://code.jquery.com/jquery-2.1.1.js"></script> </head> <body> <h2>jQuery find() demo</h2> <div>div <p> p - I am div's child</p> <span>span <p>p - I am span's Child and div's Grand Child</p></span> </div> <script> $( "div" ).find( "p" ).addClass("highlight"); </script> </body> </html> |
In this example, you can see two p
elements, one element is div
element’s child and the other one is it’s grandchild. The find() method finds all the p
element of the selected div
element and changes the color to red. Below image shows the output produced by above HTML page.
You can use selector.find("*")
to find all the descendants of the HTML document.
That’s all for now and you can find more traversing methods in the coming posts.