Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

250
Views
How to hide and display with js

How can I use javascript to toggle a class?

I attempted to colorize clicked-on text by giving the element a class, and that works (the text turns red).

But when I click on the same element twice, the class is not removed. I used toggle class for this but it doesn't seem to work.

const txts = document.querySelectorAll('.txt');

const txtColor = (txt) => {
  txt.addEventListener('click', e => {
    if (e.target.classList.contains('txt')) {
      txts.forEach(txt => txt.classList.remove('red'));
      e.target.classList.toggle('red');
    }
  });
}

txtColor(document.querySelector('ul'));
<ul>
  <li class="txt">Lorem ipsum dolor.</li>
  <li class="txt">Lorem ipsum dolor.</li>
  <li class="txt">Lorem ipsum dolor.</li>
</ul>
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You don't really need the textColor() function, so let's remove that. Then, it might be easier to compose your logic if you move the toggle function into its own function.

One place to be careful is when you are toggling the classes. In your original code, you cannot toggle the same LI off / on / off / on.

Here's why:

First, the code removes the red class from all the LIs (a good strategy) - but then, toggle is used to toggle the clicked LI's class.

Think about that... If the LI is already red, then you remove the class from all LIs (now none of them are red), then you toggle the LI that was already red, it will turn red again - and it looks like nothing happened. But it went red -> nothing -> red very, very fast. Too fast to see it happen.

Therefore, you can first check if the LI already has the red class, and only toggle it if it didn't already have that class.

This structure might help you to see it better.

const txts = document.querySelectorAll('.txt');

txts.forEach((txt) => {
  txt.addEventListener('click', (e) => toggleColor(e));
});

function toggleColor(e){
  const doRed = e.target.classList.contains('red');
  txts.forEach(txt => txt.classList.remove('red'));
  if (!doRed) e.target.classList.toggle('red');
}
.red{
  color: red;
}
li{
  user-select: none;
}
<ul>
  <li class="txt">Lorem ipsum dolor.</li>
  <li class="txt">Lorem ipsum dolor.</li>
  <li class="txt">Lorem ipsum dolor.</li>
</ul>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!