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’sclassName
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 hassomeClass
in itsclassName
string, the class is removed. Contrary-wise, if it doesn’t already have it, the class is added.obj.hasClassName(someClass)
If
obj
hassomeClass
in itsclassName
string, returnstrue
. Otherwise, returnsfalse
.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. ...
Get Facebook Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.