简体   繁体   中英

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

I imagine it's because const eCta = document.querySelector(".js-accordion-cta"); only selects the first element.

I can't seem to share the modified codepen, but I just changed the JS as below

const items = document.querySelectorAll(".js-accordion-item");
const state = "active";

items.forEach(function (item, index) {
  const eCta = item.querySelector('.js-accordion-cta')
  eCta.onclick = function () {
    
    this.classList.toggle(state);
    this.nextElementSibling.classList.toggle(state);
    
  };
});


The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM