Find number of all the children and grand children of an element with JQuery

Using .children() method of JQuery we can easily find the children of an element. But it wont go deeper. That is, It will only return the direct children of the element, not those which can be its grand-children.

For example,


If we now try to find the number of children of the element of class "header_container", we will get 1.
But if we want to get the number of all the inner children of the element of class "header_container", we can use the following function I wrote,

function count_childs(element){
 var sum = 0;

  sum += $(element).children().length;
  for(var i=0;i<$(element).children().length;i++){
   var ths = $(element).children()[i];
   if($(ths).children().length) sum += count_childs($(ths));
 return sum;
You can all the above function as,
var number_of_childs = count_childs($('.header_container'));
Now modify this function so that optionally it will return all the child elements too along with total number of child elements.

Google Recommends Recommends


Contact Us