Skip to content

Instantly share code, notes, and snippets.

@JohnRiv
Created September 23, 2011 17:41
Show Gist options
  • Save JohnRiv/1237977 to your computer and use it in GitHub Desktop.
Save JohnRiv/1237977 to your computer and use it in GitHub Desktop.
getElementsByClassName that supports native browser implementation
if (typeof RIV === 'undefined' || !RIV) {
var RIV = {};
}
RIV.utils = (function() {
return {
/**
* Gets all the DOM elements that have a specified className. Uses the native browser function if it exists.
* @param {string} classname The classname you want to search for
* @param {string} node A selector to select the scope. Defaults to "document" if not specified.
* @return {Array} classElements Array of items with the classname in the scope of node
*/
getElementsByClassName: function(classname, node) {
node = node || document;
if (node.getElementsByClassName) {
return node.getElementsByClassName(classname);
} else {
var classElements = new Array(),
els = node.getElementsByTagName("*"),
pattern = new RegExp("(^|\\s)"+classname+"(\\s|$)");
for (var i = 0, j = 0, elsLen = els.length; i < elsLen; i++) {
if ( pattern.test(els[i].className) ) {
classElements[j] = els[i];
j++;
}
}
return classElements;
}
}
};
})();
//RIV.utils.getElementsByClassName("class");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment