3 jQuery Snippets for Handling CSS Classes
CSS isn't really a very dynamic or flexible language, but with the help of jQuery, it's easy to make certain styles dynamic and changeable with just a few simple lines of code. What follows are 3 really useful and easy ways to manipulate CSS classes using jQuery.
Check for Class
In jQuery, there's a built in method that allows you check if a certain selected HTML element has any particular CSS class assigned to it. If it does, then you can execute other jQuery code (for example, removing the class, adding HTML, changing the class) based on this fact. See the snippet below for an example of how it would look to check a div for a class called ".main":
if ($("div").hasClass("main")){ Â // insert code here }
Remove Class
Removing a CSS class from an HTML element is another easy thing to do using jQuery. Often this removal of a class will happen as the result of a trigger event, and once that trigger takes place, the code to remove a class from an element will be executed. To see how to remove a class (".this-class") from a div element after it's been clicked, check out the snippet below:
$("div").click(function{ Â Â $(this).removeClass("this-class"); })
Toggle Class
You can also use jQuery to toggle between classes, meaning that you can have one class assigned to an HTML element, and then based on a trigger event (a click event like we used above, perhaps), the class can be removed. When the trigger event occurs again, the original class will be assigned to the element once more. The difference between .toggleClass and something like .removeClass is that toggle will keep removing and adding the class as the trigger event keeps occurring, but .removeClass will simply remove the class, never add it back. See the snippet below for an example of how you'd toggle the class ".toggle-class" when a div is clicked:
$("div").click(function{ Â Â $(this).toggleClass("toggle-class"); })