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

168
Visualizações
Simple javascript click to add class not working

I am trying to add / remove a class on an element that is clicked liek this

function myFunction() {
    this.classList.add("myclass");
}
#first {
  height: 100px;
  width: 100px;
  background: yellow;
  color: black;
}

.myclass {
    background: red;
    color: white;
}
<div id="first" onclick="myFunction(this)">

  Click
  
  <div class="second">
  </div>
  
  <div class="third">
  </div>
  
</div>

Why is this not working?

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

You need to pass reference this into function too like:

function myFunction(el) {
  el.classList.add("myclass");
}
#first {
  height: 100px;
  width: 100px;
  background: yellow;
  color: black;
}

.myclass {
  background: red!important;
  color: white!important;
}
<div id="first" onclick="myFunction(this)">

  Click

  <div class="second">
  </div>

  <div class="third">
  </div>

</div>

PS. add !important into css

about 4 years ago · Juan Pablo Isaza Relatório

0

Pass the this to the defined function too and check the existence of the class. Try this.

function myFunction(el) {
  if(!el.classList.contains("myclass")) {
    el.classList.add("myclass");
    console.log("added");
  } else {
    el.classList.remove("myclass");
    console.log("removed");
  }
}
#first {
  height: 100px;
  width: 100px;
  background: yellow;
  color: black;
}

.myclass {
    background: red;
    color: white;
}
<div id="first" onclick="myFunction(this)">

  Click
  
  <div class="second">
  </div>
  
  <div class="third">
  </div>
  
</div>

about 4 years ago · Juan Pablo Isaza Relatório

0

It doesn't work because this for inline handlers works differently. You can use .call, and that works... but that's still not good.

function myFunction() {
  this.classList.add("myclass");
}
#first {
  height: 100px;
  width: 100px;
  background: yellow;
  color: black;
}

.myclass {
  background: red !important;
  color: white;
}
<div id="first" onclick="myFunction.call(this)">
  Click
  <div class="second">
  </div>
  <div class="third">
  </div>
</div>

You should avoid inline script altogether and also avoid id selectors in CSS.

Change your id selector to a class selector and change your inline handler to an event listener.

Also, stray strings like "content" are a real pain as your project grows in size. Wrap them in a <span>

const myButton = document.querySelector(".first");

myButton.addEventListener("click", ({
  target
}) => target.classList.add("myclass"))
.first {
  height: 100px;
  width: 100px;
  background: yellow;
  color: black;
}

.myclass {
  background: red;
  color: white;
}
<div class="first">
  <span>Click</span>
  <div class="second"></div>
  <div class="third"></div>
</div>

about 4 years ago · Juan Pablo Isaza 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