How to change css property using javascript How to change css property using javascript javascript javascript

How to change css property using javascript


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


// 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 stylesample.style.color = 'red'; // Changes color, adds style property.// or (not recomended)sample.style = "color: red"; //Replaces all style properties. NOT RECOMENDED


Use document.getElementsByClassName('className').style = your_style.

var d = document.getElementsByClassName("left1");d.className = d.className + " otherclass";

Use single quotes for JS strings contained within an html attribute's double quotes

Example

<div class="somelclass"></div>

then document.getElementsByClassName('someclass').style = "NewclassName";

<div class='someclass'></div>

then document.getElementsByClassName("someclass").style = "NewclassName";

This is personal experience.