Count immediate child div elements using jQuery

$("#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


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").length

Direct children of the element with the id 'foo' which are divs. Then retrieving the size of the wrapped set produced.