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 onclick="myFunction()"/>
function myFunction() {
if (element.classList.contains("my-class")) {
//do something
}
}
where am I going wrong?
CodePudding user response:
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 onclick="myFunction(event)">Click me</button>
<br/>
<br/>
<br/>
<br/>
<button onclick="myFunction(event)">I Do nothing</button>
CodePudding user response:
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" >Click</div>
CodePudding user response:
When the HTML element rendered statically you should consider two things:
- Wait for the DOM ready event in order to make modifications on the element.
- Attach the event dynamically, making sure that you bind the event handler to new elements after adding them to the DOM.
HTML
<div />
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);
}
});