Monday, May 20, 2024
106
rated 0 times [  112] [ 6]  / answers: 1 / hits: 88048  / 13 Years ago, wed, september 14, 2011, 12:00:00

What is the best method to retrieve an array of elements that have a certain class?



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.



Update:



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');

More From » internet-explorer

 Answers
131

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

[#90111] Monday, September 12, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
lucianod

Total Points: 667
Total Questions: 106
Total Answers: 92

Location: Jordan
Member since Thu, Aug 5, 2021
3 Years ago
;