Quite often you achieve altering a specific HTML element’s look and feel by assigning it to a particular class, that class already possessing some customised CSS style rules in the document’s main stylesheet.
There are of course times when you actually want to achieve this visual style change on the fly, say for instance when you hover over a table row (change it’s background color for example) and the good news for you is that jQuery makes this particular ability of adding or removing classes to any element on the fly an absolute doddle.
So how is this achieved?
Well jQuery comes bundled with the handy hasClass, addClass and removeClass functions, which all do pretty much as their names suggest. The trick is to attach them to a particular selector (whichever element whose class membership you want to alter), as well as specify the name of the class that they will need to act upon.
if ( $('body').hasClass('blue') ) { $('body').removeClass('blue'); } else { $('body').addClass('blue'); }
Looking at the code above, you’ll see we’re essentially toggling the body element’s class structure, adding “blue” to it should it not already belong to that class. If however body already has the blue class instated, we then rather remove it.
It really is that simple and immediately thrusts a lot of event-driven visual manipulation power into your hands, so go forth and alter wisely my sons! :P
You might also enjoy:
-
From jQuery 1.2 onwards, the ability to tween (animate) from one color to another, in other words fade one color into a different color is as simple as inse ...
-
Using jQuery to highlight a table row on mouse over is pretty simple to achieve, and today I'll quickly demonstrate how you can achieve this neat effect usi ...
-
I’ve mentioned the wonderful jQuery plugin DataTables a number of times before, the awesome little trick that instantly transforms any HTML table fed to it ...
-
Flot is a fantastic jQuery-driven graphing engine that is extremely flexible and capable of producing some wonderfully looking and interactive graphs. To ...
-
More often than not, your HTML elements will have more than one class assigned to them. Now while it is easy to check if an element belongs to a certain cla ...