Search code examples
javascriptclasstoggleaddeventlistener

I can't remove the class I gave to the container


I tried to add a class to the text container that I click on and then the class assigns a color to the text I click on. the problem is when i click the same text twice, the class won't be removed. Any solution for this case?

PLEASE DON'T CHANGE WHERE THE CLASS IS

const contain = document.querySelector('.contain');
const inConts = document.querySelectorAll('.in-cont');

contain.addEventListener('click', e => {
  for (inCont of inConts) {
    inCont.classList.remove('red');
  }

  if (e.target.classList.contains('txt')) {
    e.target.parentElement.classList.toggle('red');
  }
});
.in-cont.red .txt {
  color: red;
}
<div class="contain">
  <div class="in-cont">
    <p class="txt">Lorem ipsum dolor sit.</p>
  </div>
  <div class="in-cont">
    <p class="txt">Lorem ipsum dolor sit.</p>
  </div>
  <div class="in-cont">
    <p class="txt">Lorem ipsum dolor sit.</p>
  </div>
</div>


Solution

  • When removing the red class, check whether inCont contains the event target:

    const contain = document.querySelector('.contain');
    const inConts = document.querySelectorAll('.in-cont');
    
    contain.addEventListener('click', e => {
      for (inCont of inConts) {
        if (!inCont.contains(e.target)) {
          inCont.classList.remove('red');
        }
      }
    
      if (e.target.classList.contains('txt')) {
        e.target.parentElement.classList.toggle('red');
      }
    });
    .in-cont.red .txt {
      color: red;
    }
    <div class="contain">
      <div class="in-cont">
        <p class="txt">Lorem ipsum dolor sit.</p>
      </div>
      <div class="in-cont">
        <p class="txt">Lorem ipsum dolor sit.</p>
      </div>
      <div class="in-cont">
        <p class="txt">Lorem ipsum dolor sit.</p>
      </div>
    </div>