Last active
August 29, 2015 14:07
-
-
Save nottrobin/e356fcba1ac4a3ef94ac to your computer and use it in GitHub Desktop.
getDescendantsByClassName
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
/** | |
* This is effectively an implementation of | |
* `element.getElementsByClassName` | |
* (see: https://developer.mozilla.org/en-US/docs/Web/API/Element.getElementsByClassName) | |
* | |
* You should probably just use the built-in method. | |
* | |
* This is therefore a partial replacement for the jQuery find() method | |
* in pure JavaScript. | |
* | |
* It extends this JSFiddle: http://jsfiddle.net/franverona/8Tx27/1/ | |
* From this StackOverflow answer: http://stackoverflow.com/a/10381659/613540 | |
*/ | |
/** | |
* Get descendants of parent by class name | |
*/ | |
function getDescendantsByClassName(parent, searchClass) { | |
var matches = []; | |
// Iterate over children | |
for (var childIndex = 0; childIndex < parent.children.length; childIndex++) { | |
var child = parent.children[childIndex]; | |
classString = child.className || ''; | |
var classes = classString.split(" "); | |
// Iterate over classes | |
for (var classIndex = 0; classIndex < classes.length; classIndex++) { | |
var childClass = classes[classIndex] | |
if (childClass == searchClass) { | |
// Save any children that have a matching class | |
matches.push(child); | |
} | |
} | |
// Add any matching child nodes of this node | |
childDescentants = getDescendantsByClass(child, searchClass); | |
matches = matches.concat(childDescentants); | |
} | |
return matches; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment