Domanda

Sono sicuro che questo è semplice, ma non ho idea di come farlo. Come faccio a contare la quantità di elementi DOM nella mia pagina HTML? Ho voluto fare questo in un userscript o bookmarklet, ma non ho idea di come iniziare!

È stato utile?

Soluzione

Usa questo per i nodi Element:

document.getElementsByTagName("*").length

Per ogni nodo, è possibile estendere Node in questo modo:

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

Poi tutto quello che dovete fare è chiamare document.countChildNodes.

Altri suggerimenti

// È possibile utilizzare lo stesso metodo per ottenere il conteggio di ogni tag, se è importante

  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 si può fare

document.getElementsByTagName("*").length

In jQuery si può fare

jQuery('*').length
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top