jQuery

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.

HTML:

<!DOCTYPE html>
<html>
<head>
<title>jQuery Add or Remove Class Dynamically</title>
<script src="https://code.jquery.com/jquery-3.4.1.js"></script>
<script type="text/javascript">
$(document).ready(function(){
  $(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(){
         optionsArr.push($(this).val());
    });
    var current_class = classArr.find( val => optionsArr.includes(val) );

    $('#myDiv').removeClass(current_class).addClass(selected_val);  
  }); 
});
</script>
</head>
<body>
<div class="container">
  <div class="selectbox">
    <select>
      <option value="small">Small</option>
      <option value="medium">Medium</option>
      <option value="large">Large</option>
    </select>
  </div>
  <div id="myDiv" class="test small">Welcome to The Code Hubs!!!!</div>
</div> 
</body> 
</html>

 

Output:

 

Rahul Chopda

Rahul Chopda is a web designer and front-end web developer with experience in HTML, CSS, jQuery also Author at TheCodeHubs.

Recent Posts

Testing hk

Testing

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

Operation

Testing

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

TETS NEW

test

2 years ago