[javascript] Count immediate child div elements using jQuery

I have the following HTML node structure:

<div id="foo">
  <div id="bar"></div>
  <div id="baz">
    <div id="biz"></div>
  </div>
  <span></span>
</div>

How do I count the number of immediate children of foo, that are of type div? In the example above, the result should be two (bar and baz).

This question is related to javascript jquery dom jquery-selectors

The answer is


In response to mrCoders answer using jsperf why not just use the dom node ?

var $foo = $('#foo');
var count = $foo[0].childElementCount

You can try the test here: http://jsperf.com/jquery-child-ele-size/7

This method gets 46,095 op/s while the other methods at best 2000 op/s


$("#foo > div") 

selects all divs that are immediate descendants of #foo
once you have the set of children you can either use the size function:

$("#foo > div").size()

or you can use

$("#foo > div").length

Both will return you the same result


In response to mrCoders answer using jsperf why not just use the dom node ?

var $foo = $('#foo');
var count = $foo[0].childElementCount

You can try the test here: http://jsperf.com/jquery-child-ele-size/7

This method gets 46,095 op/s while the other methods at best 2000 op/s


$('#foo').children('div').length

With the most recent version of jquery, you can use $("#superpics div").children().length.


$('#foo').children('div').length

$("div", "#superpics").size();

I recommend using $('#foo').children().size() for better performance.

I've created a jsperf test to see the speed difference and the children() method beaten the child selector (#foo > div) approach by at least 60% in Chrome (canary build v15) 20-30% in Firefox (v4).

By the way, needless to say, these two approaches produce same results (in this case, 1000).

[Update] I've updated the test to include the size() vs length test, and they doesn't make much difference (result: length usage is slightly faster (2%) than size())

[Update] Due to the incorrect markup seen in the OP (before 'markup validated' update by me), both $("#foo > div").length & $('#foo').children().length resulted the same (jsfiddle). But for correct answer to get ONLY 'div' children, one SHOULD use child selector for correct & better performance


var n_numTabs = $("#superpics div").size();

or

var n_numTabs = $("#superpics div").length;

As was already said, both return the same result.
But the size() function is more jQuery "P.C".
I had a similar problem with my page.
For now on, just omit the > and it should work fine.


Try this for immediate child elements of type div

$("#foo > div")[0].children.length

With the most recent version of jquery, you can use $("#superpics div").children().length.


$('#foo > div').size()

$("div", "#superpics").size();

Try this for immediate child elements of type div

$("#foo > div")[0].children.length

$("#foo > div") 

selects all divs that are immediate descendants of #foo
once you have the set of children you can either use the size function:

$("#foo > div").size()

or you can use

$("#foo > div").length

Both will return you the same result


$('#foo > div').size()

I recommend using $('#foo').children().size() for better performance.

I've created a jsperf test to see the speed difference and the children() method beaten the child selector (#foo > div) approach by at least 60% in Chrome (canary build v15) 20-30% in Firefox (v4).

By the way, needless to say, these two approaches produce same results (in this case, 1000).

[Update] I've updated the test to include the size() vs length test, and they doesn't make much difference (result: length usage is slightly faster (2%) than size())

[Update] Due to the incorrect markup seen in the OP (before 'markup validated' update by me), both $("#foo > div").length & $('#foo').children().length resulted the same (jsfiddle). But for correct answer to get ONLY 'div' children, one SHOULD use child selector for correct & better performance


$('#foo > div').size()

$("#foo > div") 

selects all divs that are immediate descendants of #foo
once you have the set of children you can either use the size function:

$("#foo > div").size()

or you can use

$("#foo > div").length

Both will return you the same result


var n_numTabs = $("#superpics div").size();

or

var n_numTabs = $("#superpics div").length;

As was already said, both return the same result.
But the size() function is more jQuery "P.C".
I had a similar problem with my page.
For now on, just omit the > and it should work fine.


var divss = 0;
$(function(){
   $("#foo div").each(function(){
    divss++;

   });
   console.log(divss);  
});     
<div id="foo">
  <div id="bar" class="1"></div>
  <div id="baz" class="1"></div>
  <div id="bam" class="1"></div>
</div>

$("#foo > div").length

jQuery has a .size() function which will return the number of times that an element appears but, as specified in the jQuery documentation, it is slower and returns the same value as the .length property so it is best to simply use the .length property. From here: http://www.electrictoolbox.com/get-total-number-matched-elements-jquery/


var divss = 0;
$(function(){
   $("#foo div").each(function(){
    divss++;

   });
   console.log(divss);  
});     
<div id="foo">
  <div id="bar" class="1"></div>
  <div id="baz" class="1"></div>
  <div id="bam" class="1"></div>
</div>

$('#foo > div').size()

$("#foo > div").length

jQuery has a .size() function which will return the number of times that an element appears but, as specified in the jQuery documentation, it is slower and returns the same value as the .length property so it is best to simply use the .length property. From here: http://www.electrictoolbox.com/get-total-number-matched-elements-jquery/


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to dom

How do you set the document title in React? How to find if element with specific id exists or not Cannot read property 'style' of undefined -- Uncaught Type Error adding text to an existing text element in javascript via DOM Violation Long running JavaScript task took xx ms How to get `DOM Element` in Angular 2? Angular2, what is the correct way to disable an anchor element? React.js: How to append a component on click? Detect click outside React component DOM element to corresponding vue.js component

Examples related to jquery-selectors

Why is my JQuery selector returning a n.fn.init[0], and what is it? How to use placeholder as default value in select2 framework Access the css ":after" selector with jQuery jQuery: using a variable as a selector Check if any ancestor has a class using jQuery jQuery selector first td of each row Select element by exact match of its content jQuery selector to get form by name jQuery : select all element with custom attribute Set select option 'selected', by value