Last active
May 3, 2016 02:15
-
-
Save Cfeusier/f0acd590f7c03a478d50 to your computer and use it in GitHub Desktop.
Recursive Reimplementation of document.getElementsByClassName
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
| var getElementsByClassName = function(className, node) { | |
| var matches = []; | |
| // top of node tree or default to body | |
| node = node || document.body; | |
| // get all classNames of node | |
| var nodeClasses = node.className.split(" "); | |
| // push node if node has className in classList | |
| nodeClasses.indexOf(className) >= 0 ? matches.push(node) : null; | |
| // if node has children, recurse | |
| if (node.children) { | |
| for (var i = 0; i < node.children.length; i++) { | |
| // add matching elements for this recursion frame | |
| matches = matches.concat(getElementsByClassName(className, node.children[i])); | |
| } | |
| } | |
| return matches; | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment