Should I use "hasClass" before "addClass"? [duplicate]
Asked Answered
R

3

115

I have come across the following script which checks whether an element has class a, and if not, adds it:

if (!$("div").hasClass("a")){
   $("div").addClass("a");
}

As jQuery won't add the class if it already exists, this could be changed to:

$("div").addClass("a");

However, is there any performance improvements by using hasClass first, or is this using the same method which addClass does anyway, and therefore duplicating the logic?

Rouvin answered 13/11, 2012 at 10:15 Comment(0)
H
185

The .hasClass() check is not useful because jQuery will also always check from within .addClass(). It's just extra work.

Hoe answered 13/11, 2012 at 10:18 Comment(1)
Thank you for a link, it is wrong line heightlighted but the function does check cur.indexOf( " " + clazz + " " ) < 0 meaning that the answer is correct.Trivial
C
13

You can see at the source code : https://github.com/jquery/jquery/blob/master/src/attributes/classes.js#L38-L45 that they do check if the class exists when using addClass.

So there is no reason to use the .hasClass() in this case.. (an exception would be if you wanted to perform more actions if the element did not have the class..)

Competent answered 13/11, 2012 at 10:22 Comment(2)
Hello from Thessaloniki and +1 -- I didn't know about the #LX-Y trick :)Hoe
Hey Jon :) It is mouse selectable as well.. (click on line number and shift+click on another to select all lines..)Competent
M
6

For what it's worth, there is a performance improvement with .hasClass() in my limited testing: http://jsperf.com/jquery-hasclass-vs-addclass-and-removeclass

However, even when standalone .removeClass() reports several times slower in Chrome, it comes in at approximately 70,000 operations a second.

Moncada answered 5/9, 2013 at 13:43 Comment(1)
Thanks, nice tool, however it is addClass in the question and removeClass in your testing.Trivial

© 2022 - 2024 — McMap. All rights reserved.