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

83
Views
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 answers
Answer question

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 Report

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 Report

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 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!