In jquery, you can use the find() method to query all descendant nodes. The find() method can return all descendant elements under the specified element (including children, grandchildren, great-grandchildren, and so on), the syntax is "$(selector).find(filter)"; the parameter "filter" is used to filter the search descendants and narrow down The range of return values. If you want to return all descendant nodes, you need to set the filter value to "*".
The operating environment of this tutorial: windows7 system, jquery3.6.1 version, Dell G3 computer.
The find() method returns all descendant elements of the selected element. (Descendants are children, grandchildren, great-grandchildren, and so on.)
DOM tree: This method traverses all paths down the DOM element's descendants to the last descendant (< ;html>).
Syntax:
$(selector).find(filter)
Parameters | Description |
---|---|
filter | Required. A selector expression, element, or jQuery object that filters search descendants. Note: To return multiple descendants, use commas to separate each expression. |
Note: The filter parameter is required in the find() method, which can reduce the scope of the return value; if you need to return all descendant elements, the filter is set to " *" Selector.
Example: Use the "*" selector to return all descendant elements of .
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <script src="js/jquery-3.6.1.min.js"></script> <script> $(document).ready(function() { $("html").find("*").css({ "color": "red", "border": "2px solid red" }); }); </script> <style> .ancestors * { display: block; border: 2px solid lightgrey; color: lightgrey; padding: 5px; margin: 15px; } </style> </head> <body class="ancestors">body (曾祖先节点) <div style="width:500px;">div (祖先节点) <ul>ul (直接父节点) <li>li (子节点) <span>span (孙节点)<span>span (曾孙节点)<span>span (曾曾孙节点)</span></span></span> </li> <li>li (子节点) <span>span (孙节点)</span> </li> </ul> </div> </body> </html>
Example: Return all elements in descendants
$(document).ready(function(){ $("ul").find("span").css({"color":"red","border":"2px solid red"}); });
[Recommended Learning: jQuery video tutorial, web front-end video】
The above is the detailed content of How to query all descendant nodes with jquery. For more information, please follow other related articles on the PHP Chinese website!