Assign Or Get Class Name Attribute With JavaScript

To get the class of an element with JavaScript you use the className property of the element object. Take the following section of HTML code.

<div id="adiv" class="theClass">some text</div>

Use the following bit of code to print off the class name of the div element in a message box.

alert(document.getElementById('adiv').className);

To set the class name to something else you can use the same property, but in this case just pass it a value. The following example changes the class name of the div element to 'newClass'.

document.getElementById('adiv').className = 'newClass';

So how is this useful? Well accessing styles can be a bit of a pain on some browsers, so a better way is to set up some styles for different classes in your style sheets and use the className property to change the class of your elements to match your styles.

For example, lets say that you wanted to create a hover effect on an element that is not an anchor. Because it isn't an anchor there are going to be some issues with IE6 and some other browsers not understanding the pseudo-class :hover, so an alternative is to use the className property to change the class so that it has a different style.

The following example uses the onmouseover and onmouseout events to create a hover like effect.

<div id="mydiv" onmouseover="changeClass(true);" onmouseout="changeClass(false);">Content</div>
 
<script type="text/javascript">
// <!--
 
function changeClass(set){
 if(set){
  document.getElementById('mydiv').className = 'bigfont';
 }else{
  document.getElementById('mydiv').className = '';
 }
}
 
// -->
</script>

The new class is called bigfont and simply has a style that has a bigger font size. Put the following into your stylesheets.

div.bigfont{
  font-size: 123px;
  border:1px solid black;
}

 

Add new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
2 + 13 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.