EN
JavaScript - add class to HTML element on click event
0
points
In this article, we would like to show you how to add class to HTML element on click event using JavaScript.
Quick solution:
<div onclick="this.classList.add('clazz')">Click me to add 'clazz' class.</div>
Where:
clazzis the name of the class that will be added on click event.
Practical example
In this example, we create addClass() function that accepts 2 arguments:
element- handle to the HTML element,clazz- class name to add.
Using the addClass() function we add yellow class to the div element.
// ONLINE-RUNNER:browser;
<!doctype html>
<html>
<head>
<style>
.yellow {
background: yellow;
}
</style>
</head>
<body>
<script>
function addClass(element, clazz) {
element.classList.add(clazz);
}
</script>
<div onclick="addClass(this, 'yellow')">Click me!</div>
</body>
</html>