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

84
Visualizações
How to detect classname with onclick event

I want to be able to click on an element and then depending on whether it has a specific class name, do something.

Here is what I have so far:

<div class="my-class" onclick="myFunction()"/>
function myFunction() {
  if (element.classList.contains("my-class")) {
    //do something
  }
}

where am I going wrong?

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

0

You need to pass the click event then get the target element which in this case is the clicked element.

function myFunction(event) {
  if (event.target.classList.contains("my-class")) {
    alert("I Do things becuase i have (my-class)")
  }
}
<button class="my-class" onclick="myFunction(event)">Click me</button>
<br/>
<br/>
<br/>
<br/>
<button onclick="myFunction(event)">I Do nothing</button>

about 4 years ago · Juan Pablo Isaza Relatório

0

As @collapsar mentioned in comment, element is't set. I recommand you to use addEventListener and event.target.

document.getElementById("your-element").addEventListener("click", () =>{
  if (event.target.classList.contains("my-class")) {
    console.log("your-element has \"my-class\" class")
  }
})
<div id="your-element" class="my-class">Click</div>

about 4 years ago · Juan Pablo Isaza Relatório

0

When the HTML element rendered statically you should consider two things:

  1. Wait for the DOM ready event in order to make modifications on the element.
  2. Attach the event dynamically, making sure that you bind the event handler to new elements after adding them to the DOM.

HTML

<div class="my-class" />

Javascript

function myFunction(event) {
  var element = event.target;
  if (element.classList.contains("my-class")) {
    //do something
  }
}

document.addEventListener("DOMContentLoaded", function(event) { 
  // DOM is ready
  const elements = document.getElementsByClassName("my-class");
  for (let i = 0; i < elements.length; i++) {
    elements[i].addEventListener('click', myFunction);
  }
});
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