To add a class to an HTML element using Javascript, the simplest way is to get the classList of the element and then use the add() method.
document.getElementById("div1").classList.add("new-class");
Let’s say I have the following HTML:
This is a paragraph.
If we want to add the class “new-class” to #div1, we can use Javascript to get the element, get the element’s classList, and then add the new class to its classList.
function clickFunction() {
var divToAddClass = document.getElementById("div1");
divToAddClass.classList.add("new-class");
}
The resulting HTML would be as follows:
This is a paragraph.
Adding a Class to an HTML Element Using Javascript With a Click
We can add a class to an HTML element using Javascript very easily by combining the add() method with a click event.
Let’s say we have the following HTML code and we want to give the user the ability to add another class to the paragraph. The new class will underline the paragraph content.
This is the paragraph we will add a class to.
Add class
We can utilize both the onclick event and the add() method to add a class to the paragraph and make the contents underlined.
Below is the Javascript code which will allow the user to be able to add a class to the paragraph:
function clickFunction() {
var currP = document.getElementById("p1");
currP.classList.add("p-new");
}
The final code and output for this example of how to add a class using Javascript is below:
Code Output:
This is the paragraph we will add a class to.
Full Code:
This is the paragraph we will add a class to.
Add class
<script>
function clickFunction() {
var currP = document.getElementById("p1");
currP.classList.add("p-new");
}
</script>
Hopefully this article has been useful for you to understand how to add a class to an HTML element using Javascript.