Implement siblings() in vanilla javascript
const colorsDiv = document.getElementById('js-colors-div');
const children = [...colorsDiv.children];
children.forEach((el) => {
el.addEventListener('click', (e) => {
children.forEach((btn) => {
btn.classList.remove('active');
})
e.target.classList.add('active');
});
});
button {
color: white
}
.yellow {
background: #ffaf00
}
.pink {
background: pink
}
.green {
background: green
}
.blue {
background: blue
}
.active {
background: black
}
<div id="js-colors-div">
<button class="yellow">yellow</button>
<button class="green">green</button>
<button class="blue">blue</button>
<button class="pink">pink</button>
</div>
In vanilla JS you could loop over the parent's children and just skip the element itself. You can use classList
methods for adding/removing the class:
this.classList.add('btn-anim');
for (let sibling of this.parentNode.children) {
if (sibling !== this) sibling.classList.remove('btn-anim');
}
Note however that you can (also in jQuery) simplify a bit: just remove the class from all buttons, and then add it to the current one:
for (let sibling of this.parentNode.children) {
sibling.classList.remove('btn-anim');
}
this.classList.add('btn-anim');
You can use previousElementSibling
and nextElementSibling
elements.
var colorsDiv = document.getElementById('js-colors-div');
var colors = colorsDiv.getElementsByTagName("button");
for (var i = 0; i < colors.length; i++) {
colors[i].addEventListener('click', function(e) {
var highlight = e.target;
//trying to achieve this
this.classList.add('btn-anim');
addClassSiblings.bind(this, 'btn-anim')();
});
}
function addClassSiblings(classNames) {
var cs = this.nextElementSibling;
while(cs) {
cs.classList.remove(classNames);
cs = cs.nextElementSibling;
}
cs = this.previousElementSibling;
while(cs) {
cs.classList.remove(classNames);
cs = cs.previousElementSibling;
}
}
.yellow {
color: yellow
}
.pink {
color: pink
}
.green {
color: green
}
.blue {
color: blue
}
.btn-anim {
color: black
}
<div id="js-colors-div">
<button class="yellow">yellow</button>
<button class="green">green</button>
<button class="blue">blue</button>
<button class="pink">pink</button>
</div>