In this example, I am experimenting with the link tags (<a>). You can apply the methods on any HTML element.
I have 3 link tags inside a <div> element. Each tag has a class property called in-active. The in-active class has default values. The idea is, when I click a link, the jQuery methods will change the CSS class of the clicked link, and the class changes to selected. The remaining two links will change back to its original class, that is in-active.
<!DOCTYPE html> <html> <head> <title>Dynamically Add or Remove CSS Class using jQuery</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script> <style> .selected { color:red; text-decoration:underlined; } .in-active { color:black; text-decoration:none; } </style> </head> <body> <p>Click the links in the box.</p> <div> <a href="#" class="in-active">Link 1</a><br /> <a href="#" class="in-active">Link 2</a><br /> <a href="#" class="in-active">Link 3</a> </div> </body> <script> $(document).ready(function () { $('a').click(function () { $('a').addClass('in-active'); // ADD CLASS TO ALL THE TAGS. if ($(this).hasClass('in-active')) { // CHECK IF THE TAG HAS 'in-active' CLASS. $(this) .removeClass('in-active') .addClass('selected'); } }) }); </script> </html>
Along with the two jQuery methods .addClass() and .removeClass(), I have also included another method in the above example, called .hasClass(). I am checking if the clicked link has the in-active class, then remove the class and add the selected class.
As I said earlier, you can apply this method to any HTML element with ease. You can add more than one class name inside the method separated by a space. For example,
$('a').addClass('class1 class2');