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

后端 未结 2 1709
故里飘歌
故里飘歌 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:43

    document.addEventListener("DOMContentLoaded", function() {
      var faqContainers = document.getElementsByClassName('faq-container');
      var faqToggle = document.getElementsByTagName('body')[0];
      for (var i = 0; i < faqContainers.length; i++) {
    
        faqContainers[i].addEventListener('click', function() {
    
          if (faqToggle.classList.contains('faq-display')) {
            faqToggle.classList.remove('faq-display');
            // alert("remove faq display!");
          } else {
            faqToggle.classList.add('faq-display');
            // alert("add faq display!");
          }
    
        });
      }
    
    
    });
    
    0 讨论(0)
  • 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')
      }
    });
    
    0 讨论(0)
提交回复
热议问题