Use vanilla javascript to add / remove class to a different element after clicking on another one

后端 未结 2 1708
故里飘歌
故里飘歌 2020-12-15 08:00

I have looked through a number of similar questions but can not find a specific example of one that answers in vanilla JS how to add and remove a class to a different elemen

2条回答
  •  时光说笑
    2020-12-15 08:55

    You need to loop:

    [...document.querySelectorAll('.faq-container')]
      .forEach(faq => faq.addEventListener('click', () => 
      document.querySelector('body').classList.toggle('faq-display')))
    

    NOTE: if you have MANY of these divs, you are better off having one event handler for a parent and test what was clicked.

    document.getElementById('faqContainerParent')
      .addEventListener('click', e => {
      const tgt = e.target;
      if (tgt.classList.contains("faq-container") || tgt.closest("div.faq-container")) { // is it the faq-container or one of the decendants
        document.querySelector('body').classList.toggle('faq-display')
      }
    });
    

提交回复
热议问题