Michael Nana
Michael Nana

Reputation: 1987

Find the number of div elements under a parent div

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

Answers (6)

dsgriffin
dsgriffin

Reputation: 68596

Pure vanilla solution:

document.getElementById('parent').querySelectorAll('div').length;

jsFiddle here.

To note: querySelectorAll() is only supported in more recent versions of IE (as of IE8+).

Upvotes: 2

Morgan ARR Allen
Morgan ARR Allen

Reputation: 10678

Without a library

document.getElementById("parent_div").children.length;

Upvotes: 1

Matt Mullens
Matt Mullens

Reputation: 2256

Try:

$('#parent').find('div').length;

Upvotes: 0

Pointy
Pointy

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

Barmar
Barmar

Reputation: 780974

This should do it:

var descendant_count = $("#parent div").length;

Upvotes: 3

Shaddow
Shaddow

Reputation: 3215

You can get number using length

$('#parent div').length

Upvotes: 0

Related Questions