How To Add And Remove Class On Click Using Data Attributes In Jquery

In this article, We will learn how to add or remove class using data attributes in jquery after a click on the button.

Please follow these steps:

  1. set data attribute name and value to the button. we used data-id=”test1″.
    Like this:

    <a class="add_button button" data-id="test1" href="#">Add Class</a>
    <a class="remove_button button" data-id="test1" href="#">Remove Class</a>
  2. set that data attribute value as a class name to the element where you want to add or remove class.
    Like this:

    <div class="test1"></div>
    <p class="test1"></p>
  3. Now first we have to get data attribute value “test1” and store in variable “id” and use it as a class selector.
    Like this:

    var id = $(this).data("id");
  4. Then adding and removing class “active” using addClass and removeClass function of jquery.
    Like this:

    $("." + id).addClass("active");
    $("." + id).removeClass("active");

Here is a full example:
HTML:

<a class="add_button button" data-id="test1" href="#">Add Class</a>
<a class="remove_button button" data-id="test1" href="#">Remove Class</a>

<div class="test1"></div>
<p class="test1"></p>

<a class="add_button button" data-id="test2" href="#">Add Class</a>
<a class="remove_button button" data-id="test2" href="#">Remove Class</a>

<div class="test2"></div>
<p class="test2"></p>

<a class="add_button button" data-id="test3" href="#">Add Class</a>
<a class="remove_button button" data-id="test3" href="#">Remove Class</a>

<div class="test3"></div>
<p class="test3"></p>

JQUERY:

$(".add_button").click(function( event ){
    event.preventDefault();
    var id = $(this).data("id");
    $("." + id).addClass("active");
});
$(".remove_button").click(function( event ){
    event.preventDefault();
    var id = $(this).data("id");
    $("." + id).removeClass("active");
});

Output:

Submit a Comment

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

Subscribe

Select Categories