jQuery: Add and Remove Element Classes on the Fly

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:

About Craig Lotter

Craig Lotter is an established web developer and application programmer, with strong creative urges (which keep bursting out at the most inopportune moments) and a seemingly insatiable need to love all things animated. Living in the beautiful coastal town of Gordon's Bay in South Africa, he games, develops, takes in animated fare, trains under the Funakoshi karate style and for the most part, simply enjoys life with his amazing wife and daughter. Oh, and he draws ever now and then too.
This entry was posted in Technology & Code, Tutorials and tagged , , , , . Bookmark the permalink.
    blog comments powered by Disqus