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
2010-02-12 04:40:03
#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
2010-02-12 04:41:30
That's good! Thanks for that catch. I actually like @Gaby's solution better.
John Weldon
2010-02-12 04:43:44
It should be `$("#foo div").size();`
Tim Down
2010-02-12 09:29:22
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
2010-02-12 15:21:13
Have to admit I haven't tested it, I was just going on normal CSS syntax.
Tim Down
2010-02-12 19:40:48
+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
2010-02-12 04:40:09
getElementsByTagName isn't available in browsers other than ones that use the Gecko engine. Try it in IE6.
amphetamachine
2010-02-12 04:46:55
@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
2010-02-12 04:50:07
@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
2010-02-12 05:06:57