I am using JavaScript and I want to add/remove a Class attribute if a button is clicked. I am able to add the class, but I don't know how to remove it. how can I do that?
window.onload = function(){
var buttonGo = document.getElementsByTagName('button')[0];
var buttonCom = document.getElementsByTagName('button')[1];
var box = document.getElementById('box');
buttonGo.onclick = function(){
box.setAttribute('class','move');
}
buttonCom.onclick = function(){
// how to remove class name?
}
}
To remove a class from an element, you use the remove() method of the classList property of the element.
The removeAttribute() method removes an attribute, and does not have a return value. The removeAttributeNode() method removes an Attr object, and returns the removed object. The result will be the same.
To remove a class from the body element, call the classList. remove() method on the body object, e.g. document.
box.removeAttribute("class")
should work.
The nicest way to set classes with Javascript is to use the className
property:
// to add
box.className = 'move';
// to remove
box.className = '';
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With