document.getelementbyid.addClass code example

Example 1: js add class

var element = document.getElementById('element');
element.classList.add('class-1');
element.classList.add('class-2', 'class-3');
element.classList.remove('class-3');

Example 2: change class javascript

Syntax:
document.getElementById('myElement').className = "myclass";

<html> 
    <head> 
        <title>Change class of an element with javascript</title> 
        <style type="text/css"> 
            .redbutton{ 
                background-color: red; 
            } 
            .greenbutton{ 
                background-color: green; 
            } 
        </style> 
        <script type="text/javascript"> 
            function changeClass() { 
                document.getElementById('clickme').className = "greenbutton"; 
                var new_class = document.getElementById('clickme').className; 
                document.getElementById('classChange').innerHTML = "New Class Name : "  
                + new_class; 
            } 
        </script> 
    </head> 
    <body> 
        <button class="redbutton" id="clickme" onclick="changeClass()" 
                    >Change Class</button><br> 
        <p id="classChange">Class Name: redbutton</p> 
    </body> 
</html>

Example 3: getelementsbyclassname add class

.newclassname {   border: 16px solid black; /* Light grey */
  border-top: 16px solid black; /* Blue */
  border-radius: 50%;
  width: 120px;
  height: 120px;
  animation: spin 2s linear infinite; }
  @keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}

Example 4: getelementsbyclassname add class

.newclassname { color: blue; }