Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

225
Visualizações
how to change class on button click in javascript

I have this script but need to have the class to be changed to "go" or "stop". currently I can turn both to change to the class but it should change to one or the other

Code

var form = document.querySelector("form");

form.addEventListener("click", function(event) {
  event.preventDefault();
  const classId = event.target.id;

  if (classId == "go") {
    event.target.className = "go";
  } else if (classId == "stop") {
    event.target.className = "stop";
  }
});
.go {
  background: green;
  color: white;
}

.stop {
  background: red;
  color: white;
}
<form action="">
  <button id="go">GO!</button>

  <button id="stop">STOP!</button>
</form>

about 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

You're adding the class to the clicked button, but never removing the class from the other button.

var form = document.querySelector("form");
const goButton = document.querySelector("#go");
const stopButton = document.querySelector("#stop");

form.addEventListener("click", function(event) {
  event.preventDefault();
  if (event.target == goButton) {
    goButton.classList.add("go");
    stopButton.classList.remove("stop");
  } else if (event.target == stopButton) {
    stopButton.classList.add("stop");
    goButton.classList.remove("go");
  }
});
.go {
  background: green;
  color: white;
}

.stop {
  background: red;
  color: white;
}
<form action="">
  <button id="go">GO!</button>

  <button id="stop">STOP!</button>
</form>

about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda