Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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>

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading