0

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?

5
  • 2
    div class="my-class" Commented Jul 4, 2022 at 12:15
  • Is it React or do you want to write class, not classname? Commented Jul 4, 2022 at 12:15
  • Also, what is element where do you declare it? Commented Jul 4, 2022 at 12:16
  • @KonradLinkowski I meant class not classname. It is written as class in my code I just wrote the wrong thing here because I'm used to react. Commented Jul 4, 2022 at 12:17
  • 1
    element does not get set in your code. Use function myFunction ( eve ) { if (eve.target.classList.contains ..... Commented Jul 4, 2022 at 12:21

3 Answers 3

2

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>

Sign up to request clarification or add additional context in comments.

Comments

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>

Comments

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);
  }
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.