How to pass this element to JavaScript onClick function and add a class to that clicked element?

Estimated read time 1 min read

To pass the clicked element to a JavaScript onClick function and add a class to that element, you can use the this keyword and the classList property.

Here’s an example:

<button class="myButton" onclick="addClass(this)">Click Me</button>

<script>
  function addClass(element) {
    element.classList.add('clicked');
  }
</script>

In this example, there is a button with an onClick event handler that calls the addClass() function. The this keyword refers to the element that was clicked (the button in this case), so when the function is called, the clicked element is passed to the function as the element argument. The function then uses the classList property of the element argument to add the clicked class to the element.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply