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

134
Visualizações
Click change color

I am working on a website and I want that when the user clicks on a specific card, it turns blue. I have searched and found some things online, but it is not working for me and I don't know why; here is the code:

<div class="card" onclick="myFunction()">
  <p class="number-card">1</p>
</div>

<script>
  function myFunction() {
    document.getElementById("card").style.backgroundcolor = "blue";
  }
</script>
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

  • You're missing an ID - anyways, use Classes instead with document.querySelectorAll(".card") MDN querySelectorAll
  • Should be backgroundColor with capital C
  • Use Element.addEventListener() instead of inline JS on* attribute handlers. JS and styles should always be in their respective tags or files, not disseminated around a HTML file.
  • Read about Event.currentTarget

<div class="card">
  <p class="number-card">1</p>
</div>

<div class="card">
  <p class="number-card">2</p>
</div>

<script>
  const changeBgColor = (ev) => {
    ev.currentTarget.style.backgroundColor = "blue";
  };
  const EL_cards = document.querySelectorAll(".card");
  EL_cards.forEach(EL => EL.addEventListener("click", changeBgColor));
</script>

Alternatively, using a regular function (where addEventListener binds by default this to the Event.currentTarget Element):

function changeBgColor() {
  this.style.backgroundColor = "blue";
}
about 4 years ago · Juan Pablo Isaza Relatório

0

You only have the class set to card but you're trying to getElementById, you should give the div an id that's unique and change the function.

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