js set class
snippet in javascript

js set class

user5698

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

addclass javascript

user3561

var element = document.getElementById("myDIV");
// to add
element.classList.add("mystyle");
// to remove
element.classList.remove("mystyle");

javascript change element class

user1957

//Overwrite all classes
element.className = "class";

//Add class
element.classList.add("class");

set class name javascript

user6094


 document.getElementById("myDIV").className = "mystyle"; 

change class javascript

user117

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>

javascript set class

user6955

const element = document.getElementById("myElementId");

element.className = "myClassName";