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.

1
<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.

1
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”.

1
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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<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.

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

Copy from hashbangcode.com

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s