Carvellis
Carvellis

Reputation: 4052

When removing a class with jQuery, is it better to include the class in the selector?

Probably this will not result in any noticable performance difference, but I was just interested. If I am removing a class on a list of elements using jQuery, is it better practice or performance to include the class in the selector?

So either include it:

$('#myList li.classToRemove').removeClass('classToRemove');

or don't include it:

$('#myList li').removeClass('classToRemove');

So basically is there any difference to narrowing the list in the selector and in the removeClass method.

Upvotes: 2

Views: 88

Answers (4)

Dave Salomon
Dave Salomon

Reputation: 3287

Sorry to bump an old post.

The test at this page seems to suggest that NOT including the class selector is around 10-15% quicker. So, if you want to use jQuery, the best approach is just:

$('#myList li').removeClass('classToRemove');
  • Note - this page does appear to use jQuery 1...

Upvotes: 0

sinemetu1
sinemetu1

Reputation: 1726

Using the more specific selector will improve performance but it won't affect the result of .removeClass().

Think of each addition to a selector like a drill down. Given the html below:

    <div id="myList">
        <ul>
            <li id="li1"></li>
            <li id="li2"></li>
            <li id="li3" class="classToRemove"></li>
        </ul>
    </div>

    //In order of fastest to slowest:
    //Selecting the exact li and calling removeClass once
    $('#li3').removeClass('classToRemove');

    //In this one we are skipping 2 li's and then calling removeClass once
    $('#myList li.classToRemove').removeClass('classToRemove');

    //In this one we have to call removeClass 3 times
    $('#myList li').removeClass('classToRemove');

Upvotes: 0

Madara&#39;s Ghost
Madara&#39;s Ghost

Reputation: 175017

Selectors are matched backwards (last to first), meaning it will first find "all elements with "classToRemove" which are also "li" which are also children of "#mylist" ".

It's done that way to narrow down the list as much as possible, as soon as possible.

Therefore, you should go with

$('#myList li.classToRemove').removeClass('classToRemove');

Less items to match means a faster, more efficient script.

Upvotes: 2

user1106925
user1106925

Reputation:

Assuming that not all the <li> elements have that class, then I'd say that it's better to run .removeClass() on the filtered set.

But overall, there will be other things that will have an impact on the performance, like...

  • The number of elements matched by '#myList li' vs '#myList li.classToRemove'

  • The way different environments optimize their DOM selection

  • The actual performance difference of the innards of the .removeClass() method between different environments

So unless you're talking about unnecessarily running .removeClass() on a large subset of elements, I wouldn't worry about it too much.

Upvotes: 2

Related Questions