A number of solutions have been built to work around browsers that don't have native getElementsByClassName. If you use any of the modern javascript libraries (e.g. jQuery, Prototype), they will automatically spackle over these browser-specific gaps.
So, for example, with jQuery:
$('.foo').get();
returns all the DOM elements with class foo, in any browser.
If you only want this particular problem solved, and don't want to use a full library, you can try using something like The Ultimate GetElementsByClassName, which lets you have:
Use GwtQuery: http://code.google.com/p/gwtquery/
A number of solutions have been built to work around browsers that don't have native
getElementsByClassName
. If you use any of the modern javascript libraries (e.g. jQuery, Prototype), they will automatically spackle over these browser-specific gaps.So, for example, with jQuery:
returns all the DOM elements with class
foo
, in any browser.If you only want this particular problem solved, and don't want to use a full library, you can try using something like The Ultimate GetElementsByClassName, which lets you have:
Although it's a couple of years old, John Resig's comparison of various solutions to the problem is still valuable.
It may be wiser to use
document.querySelector
ordocument.querySelectorAll
, supported since IE8.Have a look here:
https://developer.mozilla.org/docs/Web/API/document.querySelector https://developer.mozilla.org/docs/Web/API/document.querySelectorAll
https://developer.mozilla.org/en/DOM/document.getElementsByClassName
e: not supported natively in IE < 9, so you'd have to extend document / make a global function with something like this: http://robertnyman.com/2008/05/27/the-ultimate-getelementsbyclassname-anno-2008/ or use something like sizzle or jquery - thanks to comments below.