How to change css property using javascript

Rohan Das picture Rohan Das · Mar 6, 2013 · Viewed 175.2k times · Source

I want to change css property of class using javascript. What i actually want is when a div is hoverd, another div should become visible.

My css is like..

.left, .right{
    margin:10px;
    float:left;
    border:1px solid red;
    height:60px;
    width:60px
}
.left:hover, .right:hover{
    border:1px solid blue;
}

.center{
    float:left;
    height:60px;
    width:160px
}

.center .left1, .center .right1{
    margin:10px;
    float:left;
    border:1px solid green;
    height:60px;
    width:58px;
    display:none;
}

And html file is like..

<div class="left">
    Hello
</div>
<div class="center">
       <div class="left1">
           Bye
    </div>
       <div class="right1">
           Bye1
    </div>    
</div>
<div class="right">
    Hello2
</div>

When hello1 div is hovered, bye1 div should be visible and similarly bye2 should appear when hello2 is hovered.

http://jsfiddle.net/rohan23dec/TqDe9/1/

Answer

Ved picture Ved · Mar 6, 2013

You can use style property for this. For example, if you want to change border -

document.elm.style.border = "3px solid #FF0000";

similarly for color -

 document.getElementById("p2").style.color="blue";

Best thing is you define a class and do this -

document.getElementById("p2").className = "classname";

(Cross Browser artifacts must be considered accordingly).