There are times when you need to add/change a class for a particular element. This can be very easily achieve using the className method. Please refer to the following snippet of code to understand how it works. Explanation is given after the code.
<script type="text/javascript"> function addClass(obj) { obj.className="highlight"; } </script> <style type="text/css"> .highlight { background-color:#ccc; border:1px solid #000000; } </style> <div onclick="addClass(this);">This will be highlighted</div>
1) When user clicks the div the javascript function addClass(arg) is called and sends the reference of the element as an argument.
2) Using this object we call the javacript method className(), which takes the classname as an argument.
3) We pass the highlight class as the argument which in returns get added to the element
So if you copy paste this code into a notepad document and then save it as classtest.html then the code should work in both firefox and internet explorer
Any problems, leave a comment !!
cheers !!
Realin !



i think a better name for this function would be “overwriteClass” as the function performs no check to to see if the target object already has a class name.
in the given example, it’s obvious that the div object has no other class name, but if this function is going to be used in other pages where there might already be a class attached to the object you want to hilight, be aware that the function will overwrite any existing class, possibly creating unwanted side effects.
You can add a class to an element already with one. Instead of using a “=” use “+=” to append the class.