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 !

Share this post: