className VS classList Showdown

JavaScript performance comparison

Test case created by Jason Miller


How much faster is classList.add/remove than className regex manipulation?

Preparation code

<style type="text/css">
.foo { color:#F00; height:100px; opacity:0.3; }
.bar { color:#0F0; height:200px; opacity:0.5; }
.baz { color:#00F; height:300px; opacity:0.7; }

<div id="base" class="foo bar">
  <div class="foo bar baz">test 1</div>
  <span class="foo bar">test 2</span>
  <span class="baz">test 3</span>
Benchmark.prototype.setup = function() {
    var node = document.getElementById('base'),
        className = 'baz';
    function addClass_className(el, className) {
        var cn = el.className || '',
            c = ' '+cn+' ',
            p = ' '+className+' ';
        if (c.indexOf(p)===-1) {
            el.className = cn + (cn ? ' ' : '') + className;
    function removeClass_className(el, className) {
        var cn = el.className || '',
            c = ' '+cn+' ',
            p = ' '+className+' ';
        if (c.indexOf(p)!==-1) {
            c = c.replace(p,' ');
            el.className = c.substring(1, c.length-2);
    function addClass_classList(el, className) {
    function removeClass_classList(el, className) {

Preparation code output

test 1
test 2 test 3

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
className RegExp
addClass_className(node, className);
addClass_className(node, className);
removeClass_className(node, className);
removeClass_className(node, className);
addClass_classList(node, className);
addClass_classList(node, className);
removeClass_classList(node, className);
removeClass_classList(node, className);

Compare results of other browsers


You can edit these tests or add even more tests to this page by appending /edit to the URL. Here’s a list of current revisions for this page:


Daniel15 commented :

Using string manipulation is quicker than both ClassList and regular expressions. See and

Jason Miller (revision owner) commented :

No, your old-school method is flawed because it does not support the same functionality as classList. What if I had two CSS classes, "worldfoo" and "world"? Your example would remove only the first instance of " world", which might be "worldfoo". The following demonstrates the issue:

("bar worldfoo world baz").replace(" world","").trim()==="bar foo world baz"

Comment form temporarily disabled.

Add a comment