Last active
August 29, 2015 14:05
-
-
Save lovasoa/1812358ee57f0ce43012 to your computer and use it in GitHub Desktop.
Count nodes in a page in javascript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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