Count child elements using jQuery. JavaScript Code: var count = $("#selected p"). length; console.
It is very simple to count the number of child elements in the HTML file using jQuery. For example: If you have a parent element consisting of many children elements then you can use . length or. children().
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.
To get the count or number of child elements of a specific HTML Element using JavaScript, get reference to this HTML element, and read the childElementCount property of this HTML Element. childElementCount property returns the number of child elements in this HTML Element.
$("#foo > div").length
Direct children of the element with the id 'foo' which are divs. Then retrieving the size of the wrapped set produced.
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")
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').children('div').length
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').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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With