Skip to content

Instantly share code, notes, and snippets.

@armandocanals
Last active July 27, 2017 15:30
Show Gist options
  • Save armandocanals/9e3cebc015e93075e87c to your computer and use it in GitHub Desktop.
Save armandocanals/9e3cebc015e93075e87c to your computer and use it in GitHub Desktop.
Recursive method to find elements by class name
function getElementsByClassName(className) {
var elements = document.body,
matches = [];
function traverse(node) {
for(var i = 0; i < node.childNodes.length; i++) {
if(node.childNodes[i].childNodes.length > 0) {
traverse(node.childNodes[i]);
}
if(node.childNodes[i].getAttribute && node.childNodes[i].getAttribute('class')) {
if(node.childNodes[i].getAttribute('class').split(" ").indexOf(className) >= 0) {
matches.push(node.childNodes[i]);
}
}
}
}
traverse(elements);
return matches;
}
getElementsByClassName('some-class');
@waltershub
Copy link

you should switch the order of the conditionals on line 7 with the one on line 11 otherwise the order is a little starts from the bottom up . unless you intended that.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment