I would use document.getElementsByClassName but IE does not support it.
function _getClass(whatEverClasNameYouWant){
var a=document.getElementsByTagName('*');
for(b in a){
if((' '+a[b].className+' ').indexOf(' '+whatEverClasNameYouWant+' ')>-1){
return a[b];
}
}
}
I just want to improve querySelectorAll
fallback for IE8.
Like others answered, the simple way is adding the function to Element.prototype
with
this.querySelectorAll('.' + className);
But there are some problems:
/
, $
, *
, etc.)That means there should be some "fixing", for example:
"abcd" -> ".abcd"
"a b cd" -> ".a.b.cd"
" a b " -> ".a.b "
"a/b$c d" -> ".a\/b\$c.d"
"1234" -> ".\000031234"
this.querySelectorAll(className
.replace(/(?=[^ \w])/g, '\\') // Escape non-word characters
.replace(/\b\d/g, '\\00003$&') // Escape digits at the beginning
.replace(/(^| +)(?!$| )/g, '.') // Add "." before classes, removing spaces
);
you may create the function for older browsers
if (typeof document.getElementsByClassName!='function') {
document.getElementsByClassName = function() {
var elms = document.getElementsByTagName('*');
var ei = new Array();
for (i=0;i<elms.length;i++) {
if (elms[i].getAttribute('class')) {
ecl = elms[i].getAttribute('class').split(' ');
for (j=0;j<ecl.length;j++) {
if (ecl[j].toLowerCase() == arguments[0].toLowerCase()) {
ei.push(elms[i]);
}
}
} else if (elms[i].className) {
ecl = elms[i].className.split(' ');
for (j=0;j<ecl.length;j++) {
if (ecl[j].toLowerCase() == arguments[0].toLowerCase()) {
ei.push(elms[i]);
}
}
}
}
return ei;
}
}
IE8:
document.getElementsByClassName = function (className) {
return document.querySelectorAll('.' + className)
}
It's not a method of document:
function getElementsByClassName(node, classname) {
var a = [];
var re = new RegExp('(^| )'+classname+'( |$)');
var els = node.getElementsByTagName("*");
for(var i=0,j=els.length; i<j; i++)
if(re.test(els[i].className))a.push(els[i]);
return a;
}
tabs = getElementsByClassName(document.body,'tab'); // no document
function getElementsByClassName(className) {
if (document.getElementsByClassName) {
return document.getElementsByClassName(className); }
else { return document.querySelectorAll('.' + className); } }
Pretty sure this is the same as Leonid's function but this uses document.getElementsByClassName
when it can.