1var element = document.getElementById('element');
2element.classList.add('class-1');
3element.classList.add('class-2', 'class-3');
4element.classList.remove('class-3');
1//Overwrite all classes
2element.className = "class";
3
4//Add class
5element.classList.add("class");
1Syntax:
2document.getElementById('myElement').className = "myclass";
3
4<html>
5 <head>
6 <title>Change class of an element with javascript</title>
7 <style type="text/css">
8 .redbutton{
9 background-color: red;
10 }
11 .greenbutton{
12 background-color: green;
13 }
14 </style>
15 <script type="text/javascript">
16 function changeClass() {
17 document.getElementById('clickme').className = "greenbutton";
18 var new_class = document.getElementById('clickme').className;
19 document.getElementById('classChange').innerHTML = "New Class Name : "
20 + new_class;
21 }
22 </script>
23 </head>
24 <body>
25 <button class="redbutton" id="clickme" onclick="changeClass()"
26 >Change Class</button><br>
27 <p id="classChange">Class Name: redbutton</p>
28 </body>
29</html>