Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change css property using javascript

I want to change a CSS property of a class using JavaScript. What I actually want is when a <div> is hovered, another <div> should become visible.

.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; }
<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.

like image 821
Rohan Das Avatar asked Mar 06 '13 08:03

Rohan Das


People also ask

Can we change CSS property using JavaScript?

With JavaScript, we are able to set CSS styles for one or multiple elements in the DOM, modify them, remove them or even change the whole stylesheet for all your page.

Can we change CSS properties values using JavaScript or query?

Change CSS Property With getElementById in JavaScriptIf we have a unique id assigned to an HTML element, we can query it and change its style with the getElementById() function of the Document interface.


2 Answers

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

like image 79
Ved Avatar answered Sep 28 '22 03:09

Ved


// select element from DOM using *const* const sample = document.getElementById("myid"); // using CONST // or you can use *var* var sample = document.getElementById("myid"); // using VAR  // change css style sample.style.color = 'red'; // Changes color, adds style property. // or (not recomended) sample.style = "color: red"; //Replaces all style properties. NOT RECOMENDED 
like image 36
Tiago Rangel de Sousa Avatar answered Sep 28 '22 03:09

Tiago Rangel de Sousa