Firefox O JavaScript, cuenta el DOM


Estoy seguro de que esto es simple, pero no tengo idea de cómo hacerlo. ¿Cómo cuento la cantidad de elementos DOM en mi página HTML? Quería hacer esto en un userscript o bookmarklet pero no tengo idea de cómo empezar!

Author: Brock Adams, 2010-02-10

3 answers

Use esto para Element nodos:

document.getElementsByTagName("*").length

Para cualquier nodo, puedes extender Node así:

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

Entonces todo lo que necesitas hacer es llamar a document.countChildNodes.

 60
Author: Gumbo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-07-08 20:18:54

/ / Puedes usar el mismo método para obtener el recuento de cada etiqueta, si importa

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

Alerta (tagcensus())

 3
Author: kennebec,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-02-10 16:58:55

En JavaScript puedes hacer

document.getElementsByTagName("*").length

En jQuery puedes hacer

jQuery('*').length
 2
Author: aWebDeveloper,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-04-25 14:40:56