Class Names and JavaScript
1st of May, 2006 javascript ,
There is no DOM endorsed way to select all elements in a document by class -- like there is for element IDs. What is a poor developer to do...
There are quite a few scripts that will allow you to do exactly this, however, as with most out-of-the-box scripts they either do way too much, too little or not at all what you needed. Writing a JavaScript is quite different from writing Server-Side scripts, as there is a vast number of exceptions and incompatibilities between browsers, leaving the user as the one who loses out.
So here is my desperate cry for help, what I need is a method that:
- Allows me to find all elements of a certain class
- Change the class (or just text colour) of that element
- Change the class (or colour) back to its original if the user chooses too
I've managed to do the first two, or rather Dustin Diaz managed to do the first bit. The problem is that I have five different class names that I want to have either the original colour or to be plain black. Thus, with five classes there is a lot of code if one want to do it the hard way, and I haven't found the easy way yet. The second problem is that the changing back algorithm is not pretty -- at all. Code overhead is a major issue here.
Anyone out there have any clue whatsoever on how to solve such this?

2 Responses to “Class Names and JavaScript”
What about Robert Nymans getElementByClassName: http://www.robertnyman.com/2005/11/07/the-ultimate-getelementsbyclassname/
1Thanks, I was looking at that one a while ago, but didn’t see how it would help me. At a second glance I’ve realised that this might just do the trick as it can deal with more than one class. Dustin Diaz’s function could only do one class name at the time.
The only problem now is that I’m changing the names of all the class names that I’m traversing for - with the option to change them back. The script that I’m working on now is turning 100 lines and growing, which is not at all a good thing.
2