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.children,
elArr = Array.prototype.slice.apply(elements),
results = [];
function inspect(node, results) {
if(node.getAttribute && node.getAttribute('class')) {
if(node.getAttribute('class').split(" ").indexOf(className) >= 0) {
results.push(node);
}
};
};
elArr.forEach(function(x) {
inspect(x, results);
for(var i = 0; i < x.childNodes.length; i++) {
var node = x.childNodes[i];
inspect(node, results);
}
});
return results;
}
getElementsByClassName('central-featured-lang');
@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