Firefox Or JavaScript, count the DOM Firefox Or JavaScript, count the DOM javascript javascript

Firefox Or JavaScript, count the DOM


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.


// You could use the same method to get the count of each tag, if it matters

  function tagcensus(pa){    pa= pa || document;    var O= {},    A= [], tag, D= pa.getElementsByTagName('*');    D= A.slice.apply(D, [0, D.length]);    while(D.length){        tag= D.shift().tagName.toLowerCase();        if(!O[tag]) O[tag]= 0;        O[tag]+= 1;    }    for(var p in O){        A[A.length]= p+': '+O[p];    }    A.sort(function(a, b){        a= a.split(':')[1]*1;        b= b.split(':')[1]*1;        return b-a;    });    return A.join(', ');}

alert(tagcensus())


In JavaScript you can do

document.getElementsByTagName("*").length

In jQuery you can do

jQuery('*').length