jQuery Add / Remove Class
Adding and removing classes to/from HTML elements is super-easy with jQuery. Here is a quick tutorial that explains how it’s done. The code snippets are copy & paste friendly, so you can grab, gulp, and go.
jQuery Add Class
Here is the basic technique for adding a class to a specified element:
$('.target-element').addClass('.my-class');
This snippet adds a class named .my-class
to the specified target element, .target-element
. Here is an example where the class is added when the user clicks a button (i.e., .button
):
$('.button').click(function(){
$('.target-element').addClass('.my-class');
});
With this code, the class will be added when the user clicks the button.
jQuery Remove Class
Here is the basic technique for removing a class from a specified element:
$('.target-element').removeClass('.my-class');
This snippet removes a class named .my-class
from the specified target element, .target-element
. Here is an example where the class is removed when the user clicks a button (i.e., .button
):
$('.button').click(function(){
$('.target-element').removeClass('.my-class');
});
With this code, the class will be removed when the user clicks the button.
Note that these code snippets are using $
, which may not work depending on how you have jQuery set up. In such case, feel free to change each instance of $
to the default, jQuery
.
Bada bing bada boom.