Reputation: 2269
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';
};
Upvotes: 6
Views: 18931
Reputation: 14508
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...
.
Upvotes: 10
Reputation: 860
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')
}
Upvotes: 1
Reputation: 122085
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>
Upvotes: 11
Reputation: 68433
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.
Upvotes: 3