We can use jQuery to count the children of an element by making use of the jQuery children() method along with the JavaScript String length property.
var number_of_children = $("#div").children().length;
Let’s see this in action with a simple example.
Here we will have some HTML that will include an element with several child elements.
Some text in the div.
Some text in the div.
Some text in the div.
Some text in the div.
Some more text
As you can see in the code above, the div, #parent-div, should have 4 children, 3 div child elements and a paragraph child element.
We can use our code above to see if we get this answer.
var number_of_children = $("#parent-div").children().length;
console.log(number_of_children);
#Output
4
Let’s take a look at another example using a list.
- red
- yellow
- green
- purple
- red
- pink
- black
- orange
To see how many children are in our unordered list, we can use our code again.
var number_of_children = $("ul").children().length;
console.log(number_of_children);
#Output
8
Finally, let’s take a look at one final example using some code from the front page of this site.
Become an Expert Programmer through Interactive Examples
JavaScript
jQuery
Python
PHP
HTML
SAS
VBA
JavaScript – Featured Example
Python – Featured Example
PHP – Featured Example
jQuery – Featured Example
HTML – Featured Example
SAS – Featured Example
As you can see in this HTML example, we have many parent divs with children. Let’s use our code once again to see how many different children certain elements have.
Each variable name will be a div element in the example above.
var home_page_examples = $(".home-page-examples").children().length;
var home_nav = $(".home-nav").children().length;
var examples_container = $(".examples-container").children().length;
var examples_javascript = $(".examples-javascript").children().length;
console.log(home_page_examples);
console.log(home_nav);
console.log(examples_container);
console.log(examples_javascript);
#Output
8
7
6
1
Hopefully this article has been useful in helping you understand how to use jQuery to count the children of an element.