How can I use jQuery to find out how many children an element has?
Say I have the following structure:
<div id="container">
<div id="column1">
<div id="asset1"></div>
<div id="asset2"></div>
</div>
<div id="column2">
<div id="asset1"></div>
<div id="asset2"></div>
</div>
</div>
I want to find out how many children the div element: container, has. In this case it would return 2...
To check if an HTML element has child nodes, you can use the hasChildNodes() method. This method returns true if the specified node has any child nodes, otherwise false . Whitespace and comments inside a node are also considered as text and comment nodes.
jQuery children() MethodThe children() method returns all direct children of the selected element. The DOM tree: This method only traverse a single level down the DOM tree. To traverse down multiple levels (to return grandchildren or other descendants), use the find() method.
Use the querySelector() method to check if an element has a child with a specific id, e.g. if (box. querySelector('#child-3') !== null) {} . The querySelector method returns the first element that matches the provided selector or null of no element matches.
Answer: Use the jQuery . length property You can simply use the jQuery . length property to find the number of elements in a DIV element or any other element.
Use children
and length
:
$("#container").children().length
Use the direct children selector (>) and the length property:
$('#container > *').length
Example - http://jsfiddle.net/TtV8d/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With