Skip to content

Instantly share code, notes, and snippets.

@replete
Created April 14, 2012 14:39
Show Gist options
  • Save replete/2384841 to your computer and use it in GitHub Desktop.
Save replete/2384841 to your computer and use it in GitHub Desktop.
Get elements by class name - getElementsByClassName
/* Example usage:
var widgets = getElementsByClassName(document, "a-css-classname");
for (var i = 0; i < widgets.length; i++) {
//Do something with widgets[i]
}
*/
function getElementsByClassName(node,classname) {
if (node.getElementsByClassName) {
return node.getElementsByClassName(classname);
} else {
return (function getElementsByClass(searchClass,node) {
if ( node == null )
node = document;
var classElements = [],
els = node.getElementsByTagName("*"),
elsLen = els.length,
pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)"), i, j;
for (i = 0, j = 0; i < elsLen; i++) {
if ( pattern.test(els[i].className) ) {
classElements[j] = els[i];
j++;
}
}
return classElements;
})(classname, node);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment