Search code examples
javascriptfirefoxdombookmarkletuserscripts

Firefox Or JavaScript, count the DOM


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!


Solution

  • 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.