You can add a class to an HTML element using JavaScript by accessing the element using its ID, class, tag name, or any other suitable selector, and then using the classList
property to manipulate its classes.
For example we write:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Add Class with JavaScript</title>
<style>
.highlight {
background-color: yellow;
}
</style>
</head>
<body>
<p id="paragraph">This is a paragraph.</p>
<script>
// Select the element by ID
var paragraph = document.getElementById("paragraph");
// Add a class to the element
paragraph.classList.add("highlight");
</script>
</body>
</html>
In this example, the JavaScript code selects the <p>
element with the ID “paragraph” and adds the class “highlight” to it.
As a result, the background color of the paragraph will change to yellow according to the CSS defined for the “highlight” class.