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

157
Views
How to remove class from Button 1 when clicking on Button 2 - Vanilla JS

I am trying to make a highlight effect on Button 1 (bold and blue text with a css class). But of course the class should be removed from Button 1 when i click on another Button in the Menu.

let buttons = document.querySelectorAll(".ef-button");

for (let i = 0; i < buttons.length; i++) {

   buttons[i].addEventListener("click", function () {

      if (buttons[i].classList.contains("active-element")) {
         buttons[i].classList.remove("active-element");
      } else {
         buttons[i].classList.add("active-element");
      }

   })

}

This is what i wrote. I can click on every button to highlight it, but when i click on another button it does not remove the class from the first button... Anyways, i can click on a already highlighted button to remove the class again.

What i need is like a "reset" that removes the class from the button i clicked on.

enter image description here

When i click on Buttons:

enter image description here

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

this way:
for those who want to avoid searching in the MDN Doc1

document
.querySelectorAll('.ef-button')
.forEach( (btClickEv,_,buttons) =>
  {
  btClickEv.onclick = () =>
    buttons.forEach(bt=>bt.classList.toggle('active-element',bt===btClickEv))
  })
.ef-button       { background : pink; }
.active-element  { background : green; }
<button class="ef-button"> bt1 </button> 
<button class="ef-button"> bt2 </button> 
<button class="ef-button"> bt3 </button> 
<button class="ef-button"> bt4 </button> 
<button class="ef-button"> bt4 </button> 

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!