Firefox Or JavaScript, count the DOM

user34537 picture user34537 · Feb 10, 2010 · Viewed 11.6k times · Source

I'm sure this is simple but I have no idea how to do it. How do i count the amount of DOM elements in my HTML page? I wanted to do this in a userscript or bookmarklet but i have no idea how to start!

Answer

Gumbo picture Gumbo · Feb 10, 2010

Use this for Element nodes:

document.getElementsByTagName("*").length

For any node, you can extend Node like this:

Node.prototype.countChildNodes = function() {
  return this.hasChildNodes()
    ? Array.prototype.slice.apply(this.childNodes).map(function(el) {
        return 1 + el.countChildNodes();
      }).reduce(function(previousValue, currentValue, index, array){
        return previousValue + currentValue;
      })
    : 0;
};

Then all you need to do is to call document.countChildNodes.