The following code:
var borderTds = document.getElementsByClassName('leftborder');
gives me an error message in Internet Explorer 6, 7 and 8:
Object does not support this method
How can I select elements by their class in these browsers?
I prefer not to use JQuery.
There are several issues: Class names (and IDs) are not allowed to start with a digit. You have to pass a class to getElementsByClassName() . You have to iterate of the result set.
The getElementsByClassName method of Document interface returns an array-like object of all child elements which have all of the given class name(s). When called on the document object, the complete document is searched, including the root node.
querySelectorAll successfully removes the classes from all the elements, but getElementsByClassName only removes the classes from about half the elements.
If you want only the first element in the DOM with that class, you can select the first element out of the array returned. var elements = document. getElementsByClassName('className'); var requiredElement = elements[0];
IE6, Netscape 6+, Firefox, and Opera 7+ copy the following script in your page:
document.getElementsByClassName = function(cl) {
var retnode = [];
var elem = this.getElementsByTagName('*');
for (var i = 0; i < elem.length; i++) {
if((' ' + elem[i].className + ' ').indexOf(' ' + cl + ' ') > -1) retnode.push(elem[i]);
}
return retnode;
};
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:
document.getElementsByClassName
function.document.evaluate
function, which allows evaluation of XPath queries.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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With