Skip to content

Instantly share code, notes, and snippets.

@lovasoa
Last active August 29, 2015 14:05
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lovasoa/1812358ee57f0ce43012 to your computer and use it in GitHub Desktop.
Save lovasoa/1812358ee57f0ce43012 to your computer and use it in GitHub Desktop.
Count nodes in a page in javascript
// This beautiful oneliner is a recursive function that counts the nodes in a given node
// It uses the ES6 "=>" notation for anonymous functions
var count = (node) => 1 + Array.prototype.slice.apply(node.childNodes).reduce((p,q) => count(q)+p, 0);
// Count the number of nodes in the current document
count(document);
// Less beautiful oneliner of traditional JS that does the same thing:
function count(node) {for (var i=0,r=1;i<node.childNodes.length;i++) r+=count(node.childNodes[i]); return r}
// Count the number of nodes in the current document
count(document);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment