The power of jQuery offers many features to web developers. You can use following script to change class using jQuery.
First of all you need to have the jQuery script first. You can change the code depending on the latest version.
1 2 3 | <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"> </script> |
jQuery has addClass(), removeClass() and toggleClass() methods to change class as described below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | //Add a class $('#element').addClass('class_name'); //Remove a class $('#element').removeClass('class_name'); //Remove old class and add new class $('#element').removeClass('old_class').addClass('new_class'); //Or a short way to swap classes $("#element").toggleClass('old_class new_class'); //Set the class regardless of what it was $("#element").attr('class', 'new_class'); |
So after adding jQuery script you can use these methods in desired event to change class using jQuery like given examples.
1 2 3 4 5 | <script type="text/javascript"> $(document).ready(function(){ $('#message').removeClass('green').addClass('black'); }); </script> |
Or
1 2 3 4 5 | <script type="text/javascript"> $("button").click(function () { $('#message').attr('class', 'processing'); }); </script> |