Categories
JavaScript Answers

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

Spread the love

Sometimes, we want to pass this element to JavaScript onclick function and add a class to that clicked element.

In this article, we’ll look at how to pass this element to JavaScript onclick function and add a class to that clicked element.

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

To pass this element to JavaScript onclick function and add a class to that clicked element, we can set the onclick attribute to a function that’s called with this.

For instance, we write

<div class="row" style="padding-left: 21px">
  <ul class="nav nav-tabs" style="padding-left: 40px">
    <li class="active filter">
      <a href="#month" onclick="onClick(this)">This Month</a>
    </li>
    <li class="filter"><a href="#year" onclick="onClick(this)">Year</a></li>
    <li class="filter">
      <a href="#last60" onclick="onClick(this)">60 Days</a>
    </li>
    <li class="filter">
      <a href="#last90" onclick="onClick(this)">90 Days</a>
    </li>
  </ul>
</div>

to set the onclick attribute to the a elements to call onClick with this.

Then we define the onClick function by writing

function onClick(element) {
  element.removeClass("active");
  element.addClass("active");
}

in our JavaScript code.

We call element.removeClass to remove the 'active' class and we call addClass to add the 'active' class.

Conclusion

To pass this element to JavaScript onclick function and add a class to that clicked element, we can set the onclick attribute to a function that’s called with this.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *