How to add a class
- Previous page Toggle class
- Next page Remove class
Learn how to add a class name to an element using JavaScript.
Click the button to add the class for me!
Add class
Step 1 - Add HTML:
Add class to id="myDIV"
the div element (in this example, we use a button to add the class).
<button onclick="myFunction()">Try it</button> <div id="myDIV"> This is a DIV element. </div>
Step 2 - Add CSS:
Set the style for the specified class name:
.mystyle { width: 100%; padding: 25px; background-color: coral; color: white; font-size: 25px; }
Step 3 - Add JavaScript:
Obtain id="myDIV"
the <div> element, and add "mystyle"
Class:
function myFunction() { var element = document.getElementById("myDIV"); element.classList.add("mystyle"); }
Related pages
Tutorial:如何切换类
Tutorial:如何删除类
Reference manual:HTML DOM Element classList 属性
Reference manual:HTML DOM Element className 属性
- Previous page Toggle class
- Next page Remove class