Table of contents
Under the hood, Apollo uses the HTML5
classList API (jQuery isn’t even using this yet!) when available and fallbacks to manual class manipulation for legacy support, making it the most powerful class manipulation API on the web. HTML5
classList performance far outweighs the legacy method.
Support? IE6+ for legacy support and internal feature detection to switch to HTML5 when available. Cross-browser compatible.
I’ll talk you through the APIs for Apollo.
To add a class using Apollo, use the
addClass API, which takes an element and a single class name.
To remove a class using Apollo, use the
removeClass API, which takes an element and a single class name.
To toggle a class using Apollo, use the
toggleClass API, which takes an element and a single class name.
To test the existence of a class using Apollo, use the
hasClass API, which takes an element and a single class name. The
hasClass API returns a boolean (true/false) with the result.
Improvements from inception
When I first wrote the APIs to allow you to create your own class manipulation functions, I used some while loops, and the implementation was good, not great. I’m going to look at the removeClass function now, and show you the difference in the new API.
The old API was complex, but worked fantastically. It’s important to note than when using a library that handles classes, that it actually removes all instances and doesn’t assume the class exists just once.
The removeClass new API is part of an Object, so it’s not declared as a function like the above. As you can see, this is much cleaner, and uses one line for each removal technique too. It detects whether classList is available and rolls with that if so, or falls back to a RegExp replace on the string. The RegExp uses a ‘g’ declaration in the RegExp constructor, meaning global - and will do a global replace on the classname, removing it each time it’s present. I don’t know about you, but that’s a big improvement over file size and performance than the previous while looping.
It’s also good to note that I’ve also added the entire classList Object and native manipulation checks, and it’s still smaller than the original :)
Why not Prototype?
I originally rewrote the API to fall into a Prototype pattern, which looked like this (and you can use instead if you really want):
I’d advise against doing this though. If you’re including other libraries you might run into a lot of conflict when extending native DOM methods. It’s also considered bad practices by some to extend existing DOM by prototyping, which is exactly why I created the Apollo API.