How to get the number of DOM elements used in a web page

Javascript

Javascript Problem Overview


Using jQuery I can easily get the number of DOM elements used by a web page:

$('*').length;

But not all web sites are using jQuery.

So my question is: How do I get the number of DOM elements used in a web page using pure JavaScript and js console.

Javascript Solutions


Solution 1 - Javascript

Assuming you mean "HTMLElementNodes" as opposed to "All nodes" (which would include such things as text nodes and also be skipped by your jQuery example) then:

document.getElementsByTagName('*').length

This still requires the use of DOM though. Pure JavaScript can't interact with an HTML document other than as a string of text.

Solution 2 - Javascript

It's quite simple really:

document.getElementsByTagName('*').length

If you can ignore older browsers, you could also preserve some of the jQuery-like syntax with:

var $;
$ = document.querySelectorAll.bind(document);
$('*').length;

Solution 3 - Javascript

Using a recursive function countChildrenNumber:

function countChildrenNumber(el) {
  let result = 0
  if (el.children && el.children.length > 0) {
    result = result + el.children.length
    for (let i = 0; i < el.children.length; i++) {
      result = result + countChildrenNumber(el.children[i])
    }
  }
  return result
}

then call it by passing document as the parameter

countChildrenNumber(document)

Solution 4 - Javascript

This question is the top result on google for "js count all dom nodes" but it's 2021 now and we have ShadowDOM so none of these previous answers will actually give an accurate result.

Better to use this function which is based on the code used by Lighthouse to calculate the true DOM size.

function countNodes(element = document.body) {
  let count = 0; let child = element.firstElementChild;    
  while (child) { count += countNodes(child);
    if (child.shadowRoot) { count += countNodes(child.shadowRoot); }
    child = child.nextElementSibling; count++;
  } return count;
}

Solution 5 - Javascript

The main answer doesn't really count everything (I think shadow DOM would be excluded)

Using snippet below works better for me:

$$('*').length

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionantonjsView Question on Stackoverflow
Solution 1 - JavascriptQuentinView Answer on Stackoverflow
Solution 2 - JavascriptzzzzBovView Answer on Stackoverflow
Solution 3 - Javascriptyunfu wangView Answer on Stackoverflow
Solution 4 - JavascriptBesworksView Answer on Stackoverflow
Solution 5 - JavascriptdzhView Answer on Stackoverflow