Skip to content

Instantly share code, notes, and snippets.

@termi
Created November 1, 2012 14:33
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 termi/3993980 to your computer and use it in GitHub Desktop.
Save termi/3993980 to your computer and use it in GitHub Desktop.
getElementsByClassName-like function for all browsers (IE6+ / w3c)
var
/** @type {RegExp} @const */
RE__getElementsByClassName = /\s*(\S+)\s*/g
/** @type {string} @const */
, STRING_FOR_RE__getElementsByClassName = '(?=(^|.*\\s)$1(\\s|$))'
/** @type {boolean} @const */
, IS_IELT9 = !/\[native\s+code\]/i.test(document.getElementsByClass + "")
/** @type {RegExp} @const */
, RE__querySelector__dottes = /\./g
;
/**
* @param {(Document|Node|string)} root_or_klas if string -> klas. Class list with "." separator and start with "."
* @param {string=} klas
* @param {string=} tag
*/
function getElementsByClass(root_or_klas, klas, tag) {
var result
, preResult
, i
, child
;
if(typeof root_or_klas === "string") {
tag = klas;
klas = root_or_klas;
root_or_klas = document;
}
tag = tag || "";
if(!root_or_klas || klas == null) {
return [];
}
if("querySelectorAll" in root_or_klas) {
preResult = root_or_klas.querySelectorAll(tag + klas); // w3c and IE8
if(IS_IELT9) {
i = -1;
result = [];
while(child = preResult[++i]) {
result.push(child);
}
return result;
}
else {
return preResult;
}
}
else { // IE < 8
preResult = root_or_klas.getElementsByTagName(tag || "*");
if(klas) {
klas = klas.replace(RE__querySelector__dottes, " ");
klas = new RegExp(klas.replace(RE__getElementsByClassName, STRING_FOR_RE__getElementsByClassName));
}
i = -1;
result = [];
while(child = preResult[++i]) {
if(child.nodeType === 1 && (!klas || klas.test(child.className))) {
result.push(child);
}
}
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment