Skip to content

Instantly share code, notes, and snippets.

@davidcmoulton
Last active August 29, 2015 14:02
Show Gist options
  • Save davidcmoulton/a76949a5f35375cfbc24 to your computer and use it in GitHub Desktop.
Save davidcmoulton/a76949a5f35375cfbc24 to your computer and use it in GitHub Desktop.
Simple DOM element count
(function (window, undefined) {
// Counts all DOM elements by name & logs resulting object to console.
var forEach = Array.prototype.forEach,
counter = {},
incrementElementCount = function (elementName) {
if (counter.hasOwnProperty(elementName)) {
counter[elementName] += 1;
} else {
counter[elementName] = 1;
}
},
processNode = function (node) {
var currentNode = node;
if (currentNode.nodeType === currentNode.ELEMENT_NODE) {
incrementElementCount(currentNode.nodeName);
if (currentNode.hasChildNodes) {
forEach.call(currentNode.childNodes, function (childNode) {
if (childNode.nodeType === currentNode.ELEMENT_NODE) {
processNode(childNode);
}
});
}
}
};
processNode(window.document.firstElementChild);
console.log(counter);
}(this));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment