简体   繁体   中英

How can I count the number of elements in a DOM?

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.

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;

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;

Using document.all works on some of the browser, in future will be deprecated dont use on production.

document.all.length

Using jQuery, just in case!

$('*').length;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM