I'm working on converting jQuery to vanilla Javascript and facing a problem of siblings.
Here is my code:
const right = document.querySelector('.right');
const bullets = document.getElementsByClassName('bullets')
right.addEventListener('click', function(){
const has = document.querySelector('.swiper-pagination-bullet-active').getAttribute('aria-label');
const idx = Number(has.substr(12,1))-1;
What I want to do is if one of bullets has 'active' class, the others cannot take siblings. so wrote code like this
bullets[idx].classList.add('active');
let siblings = bullets.parentElement.children;
for(let sib of siblings) {
sib.classList.remove('active')
}
});
bullets[idx].classList.add('active');
is working, but the below codes are now working. Could anyone help me to resolve this?
CodePudding user response:
jQuery siblings()
doesn't put the element you call it on in the list. Your code does, b/c children
includes all children. bullets.parentElement
doesn't work, bullets
is list not element. For siblings of bullets[idx]
do:
bullets[idx].classList.add('active')
for(let sib of bullets[idx].parentElement.children) {
if (sib !== bullets[idx]) {
sib.classList.remove('active')
}
}
Or remove class from all children before add to bullet[idx]
.