最佳答案
I would use document.getElementsByClassName but IE does not support it.
So I tried Jonathan Snook's solution:
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;
}
var tabs = document.getElementsByClassName(document.body,'tab');
...but IE still says:
Object doesn't support this property or method
Any ideas, better methods, bug fixes?
I would prefer not to use any solutions involving jQuery or other "bulky javascript".
I got it to work!
As @joe mentioned the function is not a method of document
.
So the working code would look like this:
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;
}
var tabs = getElementsByClassName(document.body,'tab');
...Also if you only need IE8+ support then this will work:
if(!document.getElementsByClassName) {
document.getElementsByClassName = function(className) {
return this.querySelectorAll("." + className);
};
Element.prototype.getElementsByClassName = document.getElementsByClassName;
}
Use it just like normal:
var tabs = document.getElementsByClassName('tab');