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;
Share:
15,957
Admin
Author by

Admin

Updated on June 26, 2022

Comments

  • Admin
    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
    Sterling Archer almost 10 years
    Please don't abuse alert() like that.
  • Sikshya Maharjan
    Sikshya Maharjan almost 10 years
    I was about to add this approach (iPad answering...sigh, so slow), but remember the compatibility problems.
  • nickclaw
    nickclaw almost 10 years
    That's a good point to keep in mind. It does work in most current browsers though. caniuse.com/#feat=queryselector