Reputation: 685
i have a simple javascript function which removes a class from an element. The script i am using is
function removeclass(elementId, elementClass) {
document.getElementById(elementId).className = document.getElementById(elementId).className.replace( ' '+elementClass , '' );
}
The html code i am using is
<div id="mine" class="hide show success fail">Class will be removed from here</div>
<button onclick="removeclass('mine', 'fail show success')" type="button">Remove Class</button>
now i want when click on Remove Class button it should replace the passed classes one by one if they exist in the div. How can i do that ?
Upvotes: 1
Views: 49
Reputation: 6564
"not-so-much-good" solution.
function removeClass(eId, klassName) {
var el = document.getElementById(eId);
klassName.split(" ").forEach(function(e){
el.classList.remove(e);
});
}
<div id="mine" class="hide show success">Class will be removed from here</div>
<button onclick="removeClass('mine', 'success show fail show')" type="button">Remove Class</button>
Upvotes: 0
Reputation: 781004
You need to split elementClass
into an array so you can remove each one. Also, this is easier to do using the classList
property than className
.
function removeclass(elementId, elementClass) {
var classes = elementClass.split(' ');
var classList = document.getElementById(elementId).classList;
classList.remove.apply(classList, classes);
}
Upvotes: 3