Is getElementByClass safe to use across browsers like getElementById?
Update Currently using:
window.opener.document.getElementById
But I want to reference the object by classname (there will be only 1 element with that classname).
Is getElementByClass safe to use across browsers like getElementById?
Update Currently using:
window.opener.document.getElementById
But I want to reference the object by classname (there will be only 1 element with that classname).
It depends how getelementbyclass is implemented. getElementById is part of the javascript spec, and getElementByClass functionality is something you have to write or import yourself.
IIRC, getElementsByClassName
was introduced in Firefox 3, Safari 3.1, and has been in Chrome since the beginning. I don't know if/when it was added to Opera, but it isn't present in Internet Explorer at all. (Though it can be added to IE8 by extending the DOM prototypes; see Grant's answer.)
In other words, if you want a cross-browser getElementsByClassName
, you'll either need to roll your own or use a framework.
As as been mentioned by others, getElementsByClassName
is not available in Internet Explorer.
See the Customizing the DOM section of Document Object Model Prototypes, Part 1: Introduction for information on how to implement the functionality in IE.
If you really want to use it, you could test to verify if the object supports getElementsByClassname prior to using it and fall back to a JS implementation of the function if the browser doesn't support it.
prototype.js is cross-browser compliant and includes a function to get elements by class name. I know jQuery does as well (though haven't used it).
I would suggest using a wrapper library like prototype.js or jQuery, which both support a css selector model, and handle browser compatibility issues (IE6-7 being the bigger issues usually)
getElementsByClassName
is unfortunately not reliable cross-browser. It's currently supported by the most recent versions of Firefox, Opera, Safari, and Chrome, but not at all in Internet Explorer or Konqueror, according to Quirksmode.
If you want to use it cross-browser, you'll have to have to provide your own implementation for those browsers that don't support it, like in PPK's blog:
function getElementsByClassName(node,classname) {
if (node.getElementsByClassName)
return node.getElementsByClassName(classname);
else {
// your custom function
}
}