
The HTML class attribute defines one or more class names for an element.
The HTML class attribute is mainly used to point to a class in a style sheet. However, the HTML class attribute can also be used by JavaScript (HTML DOM) to make changes to HTML elements with a defined class.
Syntax:
<element class="classname">
classname – defines one or more class names for an element.
Example1:
Add classes to one HTML element:
<!DOCTYPE html>
<html>
<head>
<style>
h3.first-class {
color: #9b2226;
}
.second-class{
background-color: #e9d8a6;
}
</style>
</head>
<body>
<h3 class="first-class second-class">This is a heading.</h3>
<p>This is a paragraph.</p>
</body>
</html>
Output:
This is a heading.
This is a paragraph.
Example2:
Using JavaScript to add the “add-style” class to an element with id=”example”:
<!DOCTYPE html>
<html>
<head>
<style>
.add-style {
width: 200px;
height: 50px;
background-color: #e9d8a6;
color: #9b2226;
font-size: 20px;
}
</style>
</head>
<body>
<button onclick="addstyleFunction()">Try it</button>
<div id="example">
This is a DIV element.
</div>
<br>
<script>
function addstyleFunction() {
document.getElementById("example").classList.add("add-style");
}
</script>
</body>
</html>
Output:
Click the button to add the “add-style” class to DIV element:
This is a DIV element.
Enjoy coding!
Read also: