tags:

views:

373

answers:

2

how to count total number of divs with in a div using javascript

+1  A: 

Just use jQuery and CSS syntax:

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

Where foo is the Id of the parent div

See: http://stackoverflow.com/questions/250688/count-immediate-child-div-elements-using-jquery

John Weldon
#foo > div will only count the number of `div`'s that are a *direct* descendant. I get the idea the OP was asking about any level.
Jordan S. Jones
That's good! Thanks for that catch. I actually like @Gaby's solution better.
John Weldon
It should be `$("#foo div").size();`
Tim Down
nice, thanks Tim... that totally makes sense, CSS syntax would interpret that as any div descendant of foo... I've updated the answer.
John Weldon
Have to admit I haven't tested it, I was just going on normal CSS syntax.
Tim Down
+9  A: 

This should do it..

var top_level_div = document.getElementById('id_of_first_div');
var count = top_level_div.getElementsByTagName('div').length;

The getElementsByTageName() is not only a document method, but one that can run on any DOM element.

element.getElementsByTagName is similar to document.getElementsByTagName, except that its search is restricted to those elements which are descendants of the specified element

see more at https://developer.mozilla.org/en/DOM/element.getElementsByTagName

Gaby
getElementsByTagName isn't available in browsers other than ones that use the Gecko engine. Try it in IE6.
amphetamachine
works just fine in IE6
Gaby
I was pretty sure `getElementsByTagName` was in IE6?
alex
@amphetamachine Then I wonder why this page: http://msdn.microsoft.com/en-us/library/ms536439(VS.85).aspx says "this feature needs Microsoft Internet Explorer 5 or later" ;) `getElementsByTagName` **is** available in IE6
Doug Neiner
+1 Gaby, another great answer!
Doug Neiner
@Doug, was just copying the same link .. oh, and thanks :)
Gaby
Haha, random moment where IE6 doesn't fall over.
alex
@alex .. impressive eh ? lol
Gaby
?!? why the downvote ? oh well..
Gaby
@Gaby, its the same person that mysteriously downvoted my answer the other day... Maybe they wanted you to use RegEx to match HTML... OH MY! :)
Doug Neiner