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';
};
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';
};
Share
Improve this question
asked Oct 20, 2016 at 11:28
PersonPerson
2,26910 gold badges32 silver badges62 bronze badges
1
- have a look at this: classlist – Kevin Kloet Commented Oct 20, 2016 at 11:30
4 Answers
Reset to default 11You 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>
A generic function to set only one active element would be:
const setActive = el => {
[...el.parentElement.children].forEach(sib => sib.classList.remove('active'));
el.classList.add('active')
}
In your example:
let spans = [...document.body.querySelectorAll('.controllers > span')];
spans.forEach(el => el.addEventListener('click', e => setActive(el)))
Fiddle: https://jsfiddle.net/9j1qguac/
Update: At one point, browsers expected Array.from(el.parentElement.children)
instead of [...el.parentElement.children]
. Both are now supported, but if you start a row with a bracket, the previous row needs a semicolon. (eg a = b \n [1].map...
will be treated as a = (b[1]).map...
.
To remove a class from sibling
var el = document.getElementById( "two" );
var one = el.previousSibling();
one.classList.remove("active");
use previousSibling or nextSibling to traverse to it, and use classList.remove to remove a class.
Remove a class from an element siblings
let elem = document.getElementById('id');
let siblings = elem.parentElement.children;
for(let sib of siblings) {
sib.classList.remove('active')
}