Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add Multiple Styles with JavaScript

I want to add multiple lines of CSS with JavaScript. I know I can do this:

document.getElementById(id).style.property=new style

as in:

<!DOCTYPE html>
<html>
<body>

<h1 id="id1">My Heading 1</h1>

<button type="button" 
onclick="document.getElementById('id1').style.color = 'red'">
Click Me!</button>

</body>
</html>

But, the above code allows me add just a single CSS Property. If a want to add more than one property, like this:

#id1 {
    color: red;
    background-color: beige;
    padding-bottom: 2px;
    margin: 3px;
}

How do I add all of this by not repeating:

document.getElementById(id).style.property=new style

....again and again. Thanks in advance !

like image 727
IceWreck Avatar asked Mar 28 '16 12:03

IceWreck


2 Answers

Yes you can add multiple CSS with JavaScript like this

your button

<input id="myButton" type="button" value="Hello">

And the JavaScript for it

document.getElementById('myButton')
  .style.cssText = "color: blue; width: 100px; height: 55px; border: 1px solid red;";
like image 40
Oposyma Avatar answered Sep 28 '22 13:09

Oposyma


Here is a fiddle.

document.getElementById("id1").setAttribute(
       "style", "color: red; background-color: beige; padding-bottom: 2px; margin: 3px;");
like image 163
Thomas Sebastian Avatar answered Sep 28 '22 13:09

Thomas Sebastian