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

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.


Solution 1:

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:

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:

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)