Sometimes, we want to set a JavaScript onclick event to a class with CSS.
In this article, we’ll look at how to set a JavaScript onclick event to a class with CSS.
How to set a JavaScript onclick event to a class with CSS?
To set a JavaScript onclick event to a class with CSS, we loop through each element and set its onclick
property to the click handler.
For instance, we write
const elements = document.getElementsByClassName("someClassName");
for (const element of elements) {
element.onclick = () => {
console.log("Clicked in an element of the class.");
};
}
to select all elements with class someClassName
with getElementsByClassName
.
Then we loop through each element with a for-of loop and set their onclick
property to their click handler functions.
Conclusion
To set a JavaScript onclick event to a class with CSS, we loop through each element and set its onclick
property to the click handler.