1document.getElementById("myElementID").classList.add('myClassName');
2document.getElementById("myElementID").classList.remove('myClassName');
1document.getElementById("MyElement").classList.add('MyClass');
2
3document.getElementById("MyElement").classList.remove('MyClass');
4
5if ( document.getElementById("MyElement").classList.contains('MyClass') )
6{
7document.getElementById("MyElement").classList.toggle('MyClass');
8}
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>