jQuery: Add and Remove Element Classes on the Fly CodeUnit 22 JAN 2010

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') ) {
} else {

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

Related Posts:

About Craig Lotter

South African software architect and developer at Touchwork. Husband to a cupcake baker and father to two little girls. I don't have time for myself any more.