You can change an element's class with JavaScript by using the className
property of the element.
Here's an example:
<div id="myDiv" class="my-class"></div>
// Get the element
const myDiv = document.getElementById('myDiv');
// Change the class
myDiv.className = 'new-class';
In this example, the getElementById
method is used to get the div
element with id="myDiv"
. Then, the className
property is set to 'new-class'
, which replaces the original class of 'my-class'
with the new class.
You can also use the classList
property of the element to add, remove, or toggle classes without affecting other classes on the element. Here are some examples:
// Add a class
myDiv.classList.add('new-class');
// Remove a class
myDiv.classList.remove('my-class');
// Toggle a class
myDiv.classList.toggle('my-class');
In these examples, the classList
property is used to add or remove a class, or to toggle a class on and off. The add
method adds a class to the element's class list, the remove
method removes a class from the list, and the toggle
method adds or removes a class depending on whether it already exists on the element.
Comments
Post a Comment