Home > Software design >  How to target the next element of a NodeList with forEach?
How to target the next element of a NodeList with forEach?

Time:11-15

I apologize if my question is stupid or impossible but I am a complete beginner in JavaScript.

I have to make a carousel on my own and change the active bullet point to the next on click on the right arrow.

const bulletPoints = document.querySelectorAll('.dot')

const arrowRight = document.querySelector('.arrow_right')
arrowRight.addEventListener('click', function(event) {
  event.stopPropagation()
  console.log('arrow right click')
  bulletPoints.forEach(function(item) {
    item.classList.remove('dot_selected')
    item.nextElementSibling.classList.add('dot_selected')
  })

As you can see, for each item in my bulletPoints NodeList, I'm trying to remove the dot_selected class from the first item and add it to the next item, but I cannot. I tried with a for loop but also without success.

Thank you for your kindness.

CodePudding user response:

If you want to navigate the previous or next bullet, you just need to find the current selected index, calculate the new index, and toggle the class.

const
  bulletPoints = document.querySelectorAll('.dot'),
  arrowLeft = document.querySelector('.arrow_left'),
  arrowRight = document.querySelector('.arrow_right');

const moveTo = (event, delta) => {
  event.stopPropagation();
  const
    size = bulletPoints.length,
    currIndex = [...bulletPoints].findIndex(bullet =>
      bullet.classList.contains('dot_selected')),
    nextIndex = (currIndex   delta   size) % size;
  bulletPoints[currIndex].classList.remove('dot_selected');
  bulletPoints[nextIndex].classList.add('dot_selected');
};

arrowLeft.addEventListener('click', (e) => moveTo(e, -1));
arrowRight.addEventListener('click', (e) => moveTo(e,  1));
html, body {
  width: 100%;
  height: 100%;
  margin: 0;
}
body {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 0.5rem;
}
.dots {
  display: flex;
  flex-direction: row;
}
.dot {
  width: 1em;
  height: 1em;
}
.dot::after {
  content: '⦾';
}

.dot.dot_selected::after {
  content: '⦿';
}
<div >
  <div ></div>
  <div ></div>
  <div ></div>
  <div ></div>
</div>
<div>
  <button >Prev</button>
  <button >Next</button>
</div>

CodePudding user response:

You can get current index on a forEach function so

bulletPoints.forEach(function(item, index) {
    item.classList.remove('dot_selected');

    //check if there are another item on this NodeList
    if(bulletPoints[index 1]) {
        bulletPoints[index 1].classList.add('dot_selected');
    }
});
  • Related