Zach’s ugly mug (his face) Zach Leatherman

Quick Performance Tip: jQuery and addClass

June 30, 2009

Abstractions are helpful and dangerous. But the more we know about a library’s internals, the less danger we’ll be in later. Here’s an issue I ran into where I had assumed that jQuery would be optimized for this case, but it wasn’t. I’ll go over my bad assumption and how to workaround it.

As of jQuery 1.3.2, adding multiple HTML classes to an element using jQuery’s addClass method will add them one at a time, modifying the className property of an element for each class.

    $('#myElement').addClass('myFirstClass mySecondClass');

Here’s the original code inside of jQuery 1.3.2. Note how the classNames string is split, and elem.className is changed for each split entry.

    add: function( elem, classNames ) {
    jQuery.each((classNames || "").split(/\s+/), function(i, className){
        if ( elem.nodeType == 1 && !jQuery.className.has( elem.className, className ) )
            elem.className += (elem.className ? " " : "") + className;
        });
    },
    // ...

This may cause longer than needed delays, as reflow may occur after every class is added individually. If absolutely necessary, you can always fall back to modifying the className yourself, like so:

    $('#myElement').each(function() {
       this.className += ' myFirstClass mySecondClass';
    });

Most likely, this isn’t a tip that will be needed, but it is useful to be aware of.


< Newer
Device Independence on the Open Web
Older >
Performance Caveat with jQuery Selectors and Live Events

Zach Leatherman IndieWeb Avatar for https://zachleat.com/is a builder for the web at IndieWeb Avatar for https://fontawesome.com/Font Awesome and the creator/maintainer of IndieWeb Avatar for https://www.11ty.devEleventy (11ty), an award-winning open source site generator. At one point he became entirely too fixated on web fonts. He has given 84 talks in nine different countries at events like Beyond Tellerrand, Smashing Conference, Jamstack Conf, CSSConf, and The White House. Formerly part of CloudCannon, Netlify, Filament Group, NEJS CONF, and NebraskaJS. Learn more about Zach »

2 Comments
  1. Richard Neil Ilagan Disqus

    12 Aug 2009
    Great insight, and kudos to you for actually delving into the underlying source code.I, myself, have been writing some code that dynamically modifies classes of some HTML elements as part of an event procedure (namely, hover in and out). As you can imagine, the performance load on this can get pretty hefty; it increases proportionally the more classes you add in and the more elements you modify in one go. This is most notable in Internet Explorer too.While your aforementioned workaround for the .addClass() procedure would definitely work better in my opinion, I also wanted to ask if there was a better way to implement .removeClass() as well. Manually doing this meant string splitting and concatenation, which, I assume, is what the function already does.Good work, and definitely bookmarking this.
  2. Zach Leatherman Disqus

    14 Aug 2009
    Richard,I'm surprised you're seeing performance issues inside callbacks for hover events. How many nodes are in the DOM tree you're modifying the className for?Actually, it looks like the removeClass method is optimized, and only sets the string once, instead of multiple times. It shouldn't need any changes.elem.className = classNames !== undefined ?jQuery.grep(elem.className.split(/\s+/), function(className){return !jQuery.className.has( classNames, className );}).join(" ") :"";
Shamelessly plug your related post

These are webmentions via the IndieWeb and webmention.io.

Sharing on social media?

This is what will show up when you share this post on Social Media:

How did you do this? I automated my Open Graph images. (Peer behind the curtain at the test page)