23

これは簡単だと思いますが、どうすればいいのかわかりません。HTMLページのDOM要素の数をカウントするにはどうすればよいですか?これをユーザースクリプトまたはブックマークレットで実行したかったのですが、開始方法がわかりません。

4

3 に答える 3

60

これをElementノードに使用します。

document.getElementsByTagName("*").length

Nodeどのノードでも、次のように拡張できます。

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;
};

次に、あなたがする必要があるのは、を呼び出すことだけですdocument.countChildNodes

于 2010-02-10T12:39:15.960 に答える
3

// 重要な場合は、同じメソッドを使用して各タグの数を取得できます

  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(', ');
}

アラート(タグセンサス())

于 2010-02-10T16:24:39.733 に答える