Created
April 14, 2012 14:39
-
-
Save replete/2384841 to your computer and use it in GitHub Desktop.
Get elements by class name - getElementsByClassName
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
/* 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