tags:

views:

1850

answers:

7

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).

A: 

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.

Steerpike
+2  A: 

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.

Ben Blank
Safari and Chrome both use WebKit as HTML rendering engine.
Gumbo
That's true but they use different Javascript engines.
mishac
@Gumbo — Sure, but what's that got to do with the price of tea in China? :-)
Ben Blank
+1  A: 

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.

Grant Wagner
It looks like this only works with IE8. You can't extend `Element.prototype` or `HTMLDocument.prototype` in IE6 (or, I believe, 7).
Ben Blank
+1  A: 

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.

Hexxagonal
A: 

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).

Rake36
+1  A: 

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)

Tracker1
will jquery work in a call to window.opener though?
Blankman
if it's loaded into the opener... window.opener.$('...') works ;)
Tracker1
+3  A: 

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
    }
}
Rudd Zwolinski