I'm adding a class to an element and want to remove it from siblings. In JQuery it is simple, but how to do it the best way in plain JS? Here is an example of my code.
<div class="controllers">
<span id='one' class='active'></span>
<span id='two'></span>
<span id='three'></span>
</div>
firstBtn.onclick = function() {
slides[0].className = 'slide active';
this.className = 'active';
};
To remove all CSS classes of an element, we use removeClass() method. The removeClass() method is used to remove one or more class names from the selected element.
To remove a class from an element, you use the remove() method of the classList property of the element.
You can use loop inside click event to remove active
class from all elements and then again set it on clicked element.
var el = document.querySelectorAll('.controllers span');
for (let i = 0; i < el.length; i++) {
el[i].onclick = function() {
var c = 0;
while (c < el.length) {
el[c++].className = 'slide';
}
el[i].className = 'slide active';
};
}
.active {
color: red;
}
<div class="controllers">
<span id='one' class='active'>Lorem</span>
<span id='two'>Lorem</span>
<span id='three'>Lorem</span>
</div>
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