Reputation: 1987
Is there a jquery method that allows you to find the number of div elements under a parent node.
So say I have this set up
<div id="parent">
<div id="child1"></div>
<div id="child2"></div>
</div>
If I want to find the number of divs under parent it would be 2
or this
<div id="parent">
<div id="child1"><div id="childer1"></div></div>
<div id="child2"></div>
</div>
It should give me 3.
Is there any method that does that for you?
Upvotes: 2
Views: 4233
Reputation: 68596
Pure vanilla solution:
document.getElementById('parent').querySelectorAll('div').length;
To note: querySelectorAll()
is only supported in more recent versions of IE (as of IE8+).
Upvotes: 2
Reputation: 10678
Without a library
document.getElementById("parent_div").children.length;
Upvotes: 1
Reputation: 413709
Yes. If you want all of them:
var divs = $('#parent').find('div').length;
or
var divs = $('#parent div').length;
If you just want the immediate children:
var divs = $('#parent').children('div').length;
or
var divs = $('#parent > div').length;
The variations involving "find" and "children" are handy in case your starting element is something for which you've already got a reference.
Upvotes: 8
Reputation: 780974
This should do it:
var descendant_count = $("#parent div").length;
Upvotes: 3