Last active
July 27, 2017 15:30
-
-
Save armandocanals/9e3cebc015e93075e87c to your computer and use it in GitHub Desktop.
Recursive method to find elements by class name
This file contains 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
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('central-featured-lang'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.