Skip to content

Instantly share code, notes, and snippets.

@nottrobin
Last active August 29, 2015 14:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nottrobin/e356fcba1ac4a3ef94ac to your computer and use it in GitHub Desktop.
Save nottrobin/e356fcba1ac4a3ef94ac to your computer and use it in GitHub Desktop.
getDescendantsByClassName
/**
* 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