show hide div on click
CSS / HTML / JavaScript / jQuery

Add or Remove class in jQuery on button click

Add or Remove class in jQuery

Add or remove class using jQuery is very easy. It is one of the easiest method of jQuery. I will give you a simple example of it to make you understand.

Add or Remove class in jQuery

Example:

Include the jQuery library first.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<style>
#box{
  border:1px solid #000000;
  width:500px;
  height:500px;
}
.item{
  width:500px;
  height:500px;
}
.bg-red{
  background-color:#FF0000;
}
</style>

HTML:

<div id="box" class="item"></div>

<button type="button" id="add-color" class="btn btn-default">Add Red Color</button>

<button type="button" id="remove-color" class="btn btn-default" >Remove Red Color</button>

jQuery:

<script>
$('#add-color').on('click', function(){
  $('#box').addClass('bg-red');
});

$('#remove-color').on('click', function(){
  $('#box').removeClass('bg-red');
});
</script>

In the above example first we have create a box and two buttons. The first button will add a class bg-red and second button will remove that class. We have written the CSS accordingly to fill the background color with bg-red class.

To add or remove classes we have used addClass and removeClass methods of jQuery. We have used id selector to detect button click and on that button click we are adding and removing the classes as use can see.

Still have any question, ask in comments below. Thanks.

Author

I am a Full Stack Web Developer. I have more than 8 years of experience in the web design and development industry.

Leave a Reply

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