Home > Article > Web Front-end > How to get how many sub-elements an element has with jquery
In jquery, you can use the children() method with the length attribute to get how many child elements an element has; the children() method can return all the child elements of the selected element, and the length attribute can get the elements contained in the jquery object. The number, the syntax is "$(specified element).children().length;".
The operating environment of this article: Windows 10 system, jquery version 3.6.1, Dell G3 computer.
You can use the children method and length attribute to get how many child elements an element has.
The children() method returns all direct child elements of the selected element.
DOM tree: This method only traverses a single level down the DOM tree. To traverse down multiple levels (returning descendant nodes or other descendants), use the find() method.
Tip: To traverse a single level up the DOM tree, or to traverse all paths up to the root element of the document (returning parent nodes or other ancestors), use the parent() or parents() method.
The syntax is:
$(selector).children(filter)
The length property contains the number of elements in the jQuery object.
Syntax
$(selector).length
The example is as follows:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>123</title> <script src="js/jquery.min.js"> </script> <script> $(document).ready(function(){ var res = $("ul").children().length; $(".button2").click(function(){ $("input").val(res); }); }); </script> </head> <body>body (曾祖先节点) <div>div (祖先节点) <ul>ul (直接父节点) <li>li (子节点)</li> <li>li (子节点)</li> <li>li (子节点)</li> <li>li (子节点)</li> <li>li (子节点)</li> </ul> </div> </body> <p>数量: <input type="text" name="user"></p> <button class="button2">获取ul (直接父节点)的子元素个数</button> </html>
Output result:
Recommended related tutorials: jQuery video tutorial
The above is the detailed content of How to get how many sub-elements an element has with jquery. For more information, please follow other related articles on the PHP Chinese website!