开发者

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 w开发者_运维知识库anted to do this in a userscript or bookmarklet but i have no idea how to start!


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜