Wednesday, November 28, 2012

Handling styles and style classes using javascript - Quick guide

In this short post I am going to show you how handle styles and style classes using javascript. Having a good understanding on this is vital for any developer who works on web applications.

Ok, first assume that you have following CSS classes and a DIV as below.
<style>
 .oldClass{
    background-color:yellow;
    border:solid;
 }
 .newClass {
    background-color:green;
 }
</style>

<div id="myDiv" class="oldClass">
Content here...
</div>

As you already know you can apply a style to the div as below. (Here I am applying a background color to the DIV)

document.getElementById("myDiv").style.backgroundColor = 'red';

You know that the css property for background color is background-color. But in above javascript it is used as backgroundColor. Similarly any css property which contains hyphens are written in camel case when using with javascript as above.

Following script adds a css class to the div.
document.getElementById("myDiv").className = "newClass";

Note that if your element already has one or more css classes defined, all of them are removed when new class is applied.
Following also do the same thing, but doesn't work in IE.
document.getElementById("myDiv").setAttribute("class", 'newClass');

Below one works in IE only and also do the same thing.
document.getElementById("myDiv").setAttribute("className", 'newClass'); 


Sometimes you may need to add another class to the element without replacing the existing classes. This is how to do that.
Here both classes are applied to the DIV.
Note the space before the class name. It is required.
document.getElementById("myDiv").className += " newClass";
Here both classes are applied to the DIV.

Now assume that your div already has more than one classes applied to it like this.
<div id="myDiv" class="oldClass1 oldClass2">
    Content here...
</div>
Now think that you want to remove only the class oldClass2 .

You can simply do it as below.
document.getElementById('myDiv').className =
    (document.getElementById('myDiv').className).replace('oldClass2', '');

No comments:

Post a Comment