Add Or Remove CSS Class Dynamically In jQuery

This article shows you how to add or remove the CSS class dynamically using the jQuery. jQuery method called addClass() to add CSS class dynamically. It shows how to add class to desired elements. We can add one or more classes within the addClass() method. jQuery has provided another method called removeClass() to remove CSS class from the desired elements.


<!DOCTYPE html>
<title>jQuery Add or Remove Class Dynamically</title>
<script src=""></script>
<script type="text/javascript">
  $(document).on('change','.selectbox select',function(){
    var selected_val = $('option:selected',this).val();
    var classStr = $('#myDiv').attr('class');
    var classArr = classStr.split(" "); 
    var optionsArr = [];
    $('select option').each(function(){
    var current_class = classArr.find( val => optionsArr.includes(val) );

<div class="container">
  <div class="selectbox">
      <option value="small">Small</option>
      <option value="medium">Medium</option>
      <option value="large">Large</option>
  <div id="myDiv" class="test small">Welcome to The Code Hubs!!!!</div>




Submit a Comment

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


Select Categories