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

sdawes picture sdawes · Jan 9, 2017 · Viewed 37.4k times · Source

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 element from the one clicked on. I know it has something to do with setting up a loop and iterating through the elements, but I got lost in the exact process.

I have a number of elements with a class name of faq-container and when I click on any of them, I would like the class faq-display added to the body tag. I know I have to set up a loop like for (var i = 0; i < elements.length; i++) { elements[i].classList.remove('hover'); } but I am unsure as to exactly where to write it in the code to make this work. I have tried a number of ways but all fail.

My current script is as follows, where I simply target the first element in the array, but I want to be able to click on any of the faq-container elements and add the class name to the first and only body tag:

Answer

Pranay Kumar picture Pranay Kumar · Jan 9, 2017

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!");
      }

    });
  }


});