O'Reilly logo

Facebook Cookbook by Jay Goldman

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Manipulating CSS Class Names

Problem

I’ve done a great job of setting up my CSS so that I can make things pretty in a very modular and semantically correct fashion while keeping a flawless separation between presentation and content. But how can I apply that CSS programmatically?

Solution

In addition to the nearly standard getClassName() and setClassName() methods, Facebook has added a handful of fantastically useful methods:

obj.addClassName(newClass)

Adds the newClass class name to the object’s className string, checking first to see that it isn’t already there.

obj.removeClassName(oldClass)

Does the exact opposite of addClassName(), but you already knew that.

obj.toggleClassName(someClass)

If obj already has someClass in its className string, the class is removed. Contrary-wise, if it doesn’t already have it, the class is added.

obj.hasClassName(someClass)

If obj has someClass in its className string, returns true. Otherwise, returns false.

Note

See Manipulating DOM Elements for an explanation of why you can’t just look at the className property of an object.

Discussion

If you’re not using one of the Ajax-type libraries (which is impossible given the Sandbox renaming), manipulating CSS through JavaScript can be a bag full of pain, crammed with sharp-ended bits of code that do lots of className checking and poke you in the ribs repeatedly. Facebook’s new functions take a whole bunch of those sharp bits and round the corners off, so it’s more like a dull throbbing ache than a real hurty poke. ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required