Set multiple css style properties in Javascript

In three different methods you can set multiple style properties to an element using javascript.

for example, consider, you want to apply colour, border colour and visiblity to an element with id myElement

Method 1

document.getElementById("myElement").style.color = "#000";

document.getElementById("myElement").style.borderColor = "blue";

document.getElementById("myElement").style.visiblity = "visible";

Method 2

document.getElementById("myElement").style.cssText = "color: #000; border-color: blue; visibility: visible";

Now, the above step is going to replace the existing inline style. If you want to keep existing inline style and add these styles additionally, here is the trick

document.getElementById("myElement").style.cssText +=';'+ "color: #000; border-color: blue; visibility: visible";

Method 3

document.getElementById("demo").setAttribute("style",  "color: #000; border-color: blue; visibility: visible");

Leave a Reply

Your email address will not be published. Required fields are marked *