Changing the HTML element class name using JavaScript
In this tutorial, we are going to learn about how to change the class name of an HTML element using JavaScript.
Changing the element class name
Consider, we have a following html div
element:
<div class="container" id="first">
<h1>Hello</h1>
</div>
To change the class name of an above div
element, first we need to access it inside the JavaScript using the document.getElementById()
method then it has className
property which is used to assign a new class to an element by removing the existing classes.
const el = document.getElementById("first");
el.className = "col-12";
This above code adds col-12
class to a div
element by the removing container
class.
Updated HTML looks like this:
<div class="co1-12" id="first">
<h1>Hello</h1>
</div>
If you want to add a new class name to the element without removing the existing class names, you can use the classList.add()
method by passing the class name
as its argument.
const el = document.getElementById("first");
el.classList.add("shadow");
Updated HTML looks like this:
<div class="container shadow" id="first">
<h1>Hello</h1>
</div>
Removing the class names
If you want to remove all class names from an element, just set the empty string " "
to its className
property.
const el = document.getElementById("first");
el.className = " ";
If you want to remove a particular class name from an element instead of all classes, use the classList.remove()
method by passing the class name as an argument.
const el = document.getElementById("first");
el.classList.remove("shadow");
Changing the class names by clicking a button
If you want to change the class name of an element by clicking the button, you can do it like this.
HTML:
<div class="container" id="first">
<h1>Hello</h1>
</div>
<button id="change">Change class name</button>
JavaScript:
const el = document.getElementById("first"); // div element
const btn = document.getElementById("change"); // button element
// attaching a click event to the button element
btn.addEventListener("click", ()=>{
el.className = "col-12";
})
Similarly, you can also remove the class names of an element by clicking a button like this:
HTML:
<div class="container" id="first">
<h1>Hello</h1>
</div>
<button id="remove">Remove class name</button>
JavaScript:
const el = document.getElementById("first"); // div element
const btn = document.getElementById("remove"); // button element
// attaching a click event to the button element
btn.addEventListener("click", ()=>{
el.className = " "; // removes the `container` class
})