for loop over elements in vanilla javascript – only the first element in the accordion works

I’m working on a small accordion component. I know how to make it work in jQuery using this code:

const eCta    = $('.js-accordion-cta');
const eTarget = $('.js-accordion-target');
const state   = 'active';

eCta.on('click', function(){
   $(this).next(eTarget).toggleClass(state);
   $(this).toggleClass(state);
});

I wan’t to avoid using external libraries like jQuery but I can’t get it to work with js. It only works on the first element in the accordion.

const item = document.querySelectorAll(".js-accordion-item");
const eCta = document.querySelector(".js-accordion-cta");
const eTarget = document.querySelector(".js-accordion-target");
const state = "active";

item.forEach(function (item, index) {
  
  eCta.onclick = function () {
    
    this.classList.toggle(state);
    this.nextElementSibling.classList.toggle(state);
    
  };
  
});

<div class="item js-accordion-item">

    <a class="cta js-accordion-cta">Accordion Title 1 (cta)</a>

    <div class="target js-accordion-target">
      <h3>Lorem ipsum item</h3>
      <p>Content lorem ipsum dolor sit amet, consectetur adipiscing elit </p>
    </div>

</div>
  
<div class="item js-accordion-item">
...

What is the correct way to loop over dom items to interact with them? Preferable in ES6

Codepen demo

71 thoughts on “for loop over elements in vanilla javascript – only the first element in the accordion works”

Leave a Comment