Step 1) Add HTML :
<button onclick="myFunction()">Try it</button>
<div id="myDIV">
This is a DIV element.
</div>
Step 2) Add CSS :
.mystyle {
width: 100%;
padding: 25px;
background-color: coral;
color: white;
font-size: 25px;
}
Step 3) Add JavaScript :
function myFunction() {
var element = document.getElementById("myDIV");
element.classList.add("mystyle");
}
Cross-browser solution :
Note: The classList property is not supported in Internet Explorer 9. The following code will work in all browsers:
function myFunction() {
var element, name, arr;
element = document.getElementById("myDIV");
name = "mystyle";
arr = element.className.split(" ");
if (arr.indexOf(name) == -1) {
element.className += " " + name;
}
}