javascript document.getElementsByClassName compatibility with IE
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
IE 11: Object doesn't support property or method 'getElementsByClassName'
The fix is as follows:
<meta http-equiv="X-UA-Compatible" content="IE=11" />
getElementsByClassName Iexplorer compatibility
I would forget about .getElementsByClassName()
and stick with .querySelectorAll()
, which works very similarly to jQuery selectors. Works perfectly in IE8 with CSS2 selectors:
var elements = document.querySelectorAll('.myClass');
You can create your own reusable selector from it too:
var $$ = function (selector) {
return document.querySelectorAll(selector);
};
// usage
$$('#id');
$$('.className');
$$('[attributes]');
getElementsByClassName and IE9
You're probably in quirks or compatibility mode. IE9 requires standards mode.
Don't forget your <!doctype html>
at the top of the HTML document, and perhaps <meta http-equiv="X-UA-Compatible" content="IE=edge" />
in the <head>
.
getElementsByClassName in ie8
Here is a quick solution by extending the Element.prototype
and the document
:
(function() {
if (!document.getElementsByClassName) {
var indexOf = [].indexOf || function(prop) {
for (var i = 0; i < this.length; i++) {
if (this[i] === prop) return i;
}
return -1;
};
getElementsByClassName = function(className, context) {
var elems = document.querySelectorAll ? context.querySelectorAll("." + className) : (function() {
var all = context.getElementsByTagName("*"),
elements = [],
i = 0;
for (; i < all.length; i++) {
if (all[i].className && (" " + all[i].className + " ").indexOf(" " + className + " ") > -1 && indexOf.call(elements, all[i]) === -1) elements.push(all[i]);
}
return elements;
})();
return elems;
};
document.getElementsByClassName = function(className) {
return getElementsByClassName(className, document);
};
if(Element) {
Element.prototype.getElementsByClassName = function(className) {
return getElementsByClassName(className, this);
};
}
}
})();
It's not always, however, the best idea to extend the prototype object, especially with a function named exactly like a non-existent native function. If you want to escape the problems caused by extension of the prototype, use this code:
(function() {
var indexOf = [].indexOf || function(prop) {
for (var i = 0; i < this.length; i++) {
if (this[i] === prop) return i;
}
return -1;
};
window.getElementsByClassName = function(className,context) {
if (context.getElementsByClassName) return context.getElementsByClassName(className);
var elems = document.querySelectorAll ? context.querySelectorAll("." + className) : (function() {
var all = context.getElementsByTagName("*"),
elements = [],
i = 0;
for (; i < all.length; i++) {
if (all[i].className && (" " + all[i].className + " ").indexOf(" " + className + " ") > -1 && indexOf.call(elements,all[i]) === -1) elements.push(all[i]);
}
return elements;
})();
return elems;
};
})();
That way, you can safely use a getElementsByClassName()
function that accepts two arguments:
className
: the CSS classcontext
: the node
getElementsByClassName() doesn't work in old Internet Explorers like IE6, IE7, IE8
This solution may help. This is a custom getElementsByClassName
function implemented in pure javascript, that works in IE.
Essentially what this script is doing is probing, one by one, all possible options and picks the best one available. These options are:
- Native
document.getElementsByClassName
function. document.evaluate
function, which allows evaluation of XPath queries.- Traversing the DOM tree.
Of course the first one is the best performance-wise, however the latter should be available everywhere including IE 6.
Usage example, which is also available on the page, looks like this:
getElementsByClassName("col", "div", document.getElementById("container"));
So the function allows 3 parameters: class (required), tag name (optional, searches for all tags if not specified), root element (optional, document if not specified).
Update. The solution linked in the blog post is hosted on the Google Code which is shutting down in Jan 2016. However the author has made it available on GitHub. Kudos to flodin pointing this out in the comments.
getElementsByClassName performance in Google Chrome and Internet Explorer
IE8 and under doesn't support getElementsByClassName()
, but there's three options you can try.
1: You could create a function
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;
}
And use the function like this
var classone = getElementsByClassName(document.body,'classone'); // no document
2: You can use jQuery.
var classone = $('.classone');
3: You can use the querySelectorAll()
method/function.
var classone = querySelectorAll('.classone');
Related Topics
What's the Significant Use of Unary Plus and Minus Operators
Does IE9 Support Console.Log, and Is It a Real Function
JavaScript Regex - Look Behind Alternative
How to Add New Array Elements at the Beginning of an Array in JavaScript
How to Pass Data from a Page to Another Page Using React Router
When to Use Vanilla JavaScript VS. Jquery
Selecting Null: What Is the Reason Behind Selectall(Null) in D3
What Is Minimum Millisecond Value of Settimeout
Difference Between Dates in JavaScript
Execute Script After Specific Delay Using JavaScript
Underscore Template Throwing Variable Not Defined Error
What Is Meant by 'First Class Object'
Call ASP.NET Function from JavaScript
Jquery's Jquery-1.10.2.Min.Map Is Triggering a 404 (Not Found)
Long Processing Time Likely Due to Getvalue and Cell Inserts
Reactjs - Does Render Get Called Any Time "Setstate" Is Called
When You Pass 'This' as an Argument
How to Convert an Array of Objects to Object with Key Value Pairs