How can I count the number of elements in a DOM?
15,957
Solution 1
The easiest way is simply:
var numOfElements = document.getElementsByTagName('*').length;
Or, to find those elements within a given element:
var element = document.getElementById('demo'),
numElems = element.getElementsByTagName('*').length;
Solution 2
You can use querySelectorAll
to quickly select elements using CSS selectors. You you want to count every single element you can just do:
var num = document.querySelectorAll('*').length;
If you want to count all elements in a div you can do this:
var num = document.querySelectorAll('#id *').length;
Author by
Admin
Updated on June 26, 2022Comments
-
Admin almost 2 years
I'd like to learn to count the number of elements in the body or within a specific div in my DOM with javascript. What's a simple way to do this accurately?
There don't seem to be any tutorials for this that I can find, so I figured it'd be a good question for SO.
-
Sterling Archer almost 10 yearsPlease don't abuse
alert()
like that. -
Sikshya Maharjan almost 10 yearsI was about to add this approach (iPad answering...sigh, so slow), but remember the compatibility problems.
-
nickclaw almost 10 yearsThat's a good point to keep in mind. It does work in most current browsers though. caniuse.com/#feat=queryselector