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: