HTML5 classList API

By  on  

Having thrust myself into the world of JavaScript and JavaScript Libraries, I've often wondered: When are browser vendors going to see the helper methods/libraries created by the JavaScript toolkits and implement these functionalities natively within the browser? I realize that standards are important and browser vendors can't afford to half-ass these implementations but I do believe they could be...expedited.  The good news is that one of these functionalities has been add to the HTML5 API; classList.

The classList object, added to all nodes within the DOM, provides developers methods by which to add, remove, and toggle CSS classes on a node.  classList also allows developers to check if a CSS class has been assigned to a given node.

Element.classList

The classList object contains a number of helpful methods:

{
	length: {number}, /* # of class on this element */
	add: function() { [native code] },
	contains: function() { [native code] },
	item: function() { [native code] }, /* by index */
	remove: function() { [native code] },
	toggle: function() { [native code] }
}

Element.classList, as you can see, is a small but useful collection of methods.

Adding a CSS Class

The add method allows you to add one more multiple space-separated classes:

myDiv.classList.add('myCssClass');

Removing a CSS Class

The add method allows you to remove a single class:

myDiv.classList.remove('myCssClass');

You could separate multiple classes by space but the result may not be incredibly reliable.

Toggling a CSS Class

myDiv.classList.toggle('myCssClass'); //now it's added
myDiv.classList.toggle('myCssClass'); //now it's removed

Note: If toggle is called and the element does not have the provided CSS class, the class is added.

Contains CSS Class Check

myDiv.classList.contains('myCssClass'); //returns true or false

The classList API is now supported by all modern browsers, so look for the JavaScript libraries to include classList checks instead of parsing an element's class attribute!

Recent Features

  • By
    Introducing MooTools Templated

    One major problem with creating UI components with the MooTools JavaScript framework is that there isn't a great way of allowing customization of template and ease of node creation. As of today, there are two ways of creating: new Element Madness The first way to create UI-driven...

  • By
    How to Create a RetroPie on Raspberry Pi – Graphical Guide

    Today we get to play amazing games on our super powered game consoles, PCs, VR headsets, and even mobile devices.  While I enjoy playing new games these days, I do long for the retro gaming systems I had when I was a kid: the original Nintendo...

Incredible Demos

  • By
    PHP IMDB Scraper

    It's been quite a while since I've written a PHP grabber and the itch finally got to me. This time the victim is the International Movie Database, otherwise known as IMDB. IMDB has info on every movie ever made (or so it seems). Their...

  • By
    Send Email Notifications for Broken Images Using MooTools AJAX

    One of the little known JavaScript events is the image onError event. This event is triggered when an image 404's out because it doesn't exist. Broken images can make your website look unprofessional and it's important to fix broken images as soon as possible.

Discussion

  1. I feel it’s going to be a standard that won’t be implemented for a long time to come across all vendors, but it is certainly worth the wait. And at least we have libraries to fall back on for the moment.

    Just wish that there was one JavaScript engine and all used it. Only in a perfect world I guess, and that would also apply for CSS(3) etc.

  2. @Alex Hall: I hope that’s not the case — seems *very* easy to implement.

  3. Aubrey

    @Alex Hall:
    I wish there was one browser and all used it. That’d be bliss! :)

    • The last time there was one browser that everyone used we were left with years of stagnation. Perhaps you’ve forgotten about IE6?

  4. Jani Peltoniemi

    It’s a step forward, but I prefer Mootools’ Element.addClass over Element.classList.add

  5. @Jani Peltoniemi: I do too, but MooTools could (and probably will, once more browsers implement classList) use these native methods to more quickly add/remove/toggle classes.

  6. very good! Has now come true?

  7. Feature test for HTML5 classList:

    if (!!document.createElement('p').classList) {
     // native classList support
    };
    • mathias, the more ‘accepted’ way to test for such properties is:

      'classList' in document.createElement('p')

      This way also properties that are 0 or false or empty string or null are found. (In this case it doesn’t matter because the classList object never evaluates to false, but still…)

  8. That’s good stuff, but hmm chaining seems not working (FF4):

    element.classList.add("added-class").remove("removed-class");
    

    does not work :/

    If there is room for improvement, I wish toggle, remove and add would be available for chaining. What you guys think?

  9. Supported browsers includes Firefox and Google Chrome. Maybe Safari too? I am not sure about that…
    Thanks for the great article!

  10. With all these modern API implementations, programming JavaScript will be boring soon ;)

  11. Maybe I’m just missing it…but there’s no timestamps for the blog post or comments? I’m sure there’s an editorial aesthetic behind it, but it makes it hard to evaluate statements such as “Mozilla Firefox is the only browser that currently supports the classList API.”

    I only take the time to complain because the post overall is an excellent reference :)

  12. Kyle A. Matheny

    Just an update:
    All modern browsers now support classList. IE is lacking, as usual.

    http://caniuse.com/#search=classList

    • IE10+ supports classList.

    • FYI IE11 doesn’t support the optional 2nd add/remove param to classList.toggle.

  13. 645268865

  14. Woohoo. I just used this on a live project. We’re finally getting somewhere :))

  15. I’m having a problem with the classList in the following situation.

    I want to user querySelectorAll() to give all the elements an specific class. But that doesn’t work. Even when i use an for loop.

    Do you know how to do it? Would be great if you can point me in the right direction! :-)

    • Jimmie
      document.querySelectorAll('.classname.hide').forEach((node) => node.classList.remove('hide'));
      

      Works fine for me

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!