Skip to content

Instantly share code, notes, and snippets.

@Cfeusier
Last active May 3, 2016 02:15
Show Gist options
  • Select an option

  • Save Cfeusier/f0acd590f7c03a478d50 to your computer and use it in GitHub Desktop.

Select an option

Save Cfeusier/f0acd590f7c03a478d50 to your computer and use it in GitHub Desktop.
Recursive Reimplementation of document.getElementsByClassName
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