You have the following choices:
- Use
document.getElementsByClassName("xyz")
. This will return a NodeList (like an array) of objects that have that class name. Unfortunately, this function does not exist in older versions of IE.
- Use
document.getElementsByTagName("span")
and then loop over those objects, testing the .className
property to see which ones have the desired class.
- Use
document.querySelectorAll(".xyz")
to fetch the desired objects with that class name. Unfortunately this function does not exist in older browsers.
- Get a library that automatically handles all CSS3 selector queries in all browsers. If you want just a selector library, then you can use Sizzle. If you want a more comprehensive library for manipulating the DOM, then use YUI3 or jQuery (both of which have Sizzle built-in).
As of 2011, my advice is option #4. Unless this is a very small project, your development productivity will improve immensely by using a CSS3 selector library that has already been developed for cross-browser use. For example in Sizzle, you can get an array of objects with your class name with this line of code:
var list = Sizzle(".xyz");
In jQuery, you can create a jQuery object that contains a list of objects with that class with this line of code:
var list = $(".xyz");
And, both of these will work in all browsers since IE6 without you having to worry about any browser compatibility.
In more modern times (like 2021), you can use built in document.querySelectorAll()
and see fairly rich CSS3 selector support.