Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery: How to find out how many children an element has?

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...

like image 513
Antonio Moore Avatar asked Apr 18 '12 09:04

Antonio Moore


People also ask

How can you tell how many children an element has?

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.

How do you get children of children in jQuery?

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.

How do I check if a div has a child?

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.

How do I count the number of elements in jQuery?

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.


2 Answers

Use children and length:

$("#container").children().length
like image 120
T.J. Crowder Avatar answered Oct 17 '22 06:10

T.J. Crowder


Use the direct children selector (>) and the length property:

$('#container > *').length

Example - http://jsfiddle.net/TtV8d/

like image 29
Richard Dalton Avatar answered Oct 17 '22 06:10

Richard Dalton