Learn how to add a class name to an element with JavaScript.
Add a class name to the div element with id="myDIV" (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>
Style the specified class name:
.mystyle {
width: 100%;
padding: 25px;
background-color: coral;
color: white;
font-size: 25px;
}
Get the <div> element with id="myDIV" and add the "mystyle" class to it:
function myFunction() {
var element = document.getElementById("myDIV");
element.classList.add("mystyle");
}
Try it Yourself »
Tip: Also see How To Toggle A Class.
Tip: Also see How To Remove A Class.
Tip: Learn more about the classList property in our JavaScript Reference.
Tip: Learn more about the className property in our JavaScript Reference.
截取页面反馈部分,让我们更快修复内容!也可以直接跳过填写反馈内容!