Should I use "hasClass" before "addClass"?

JqueryPerformanceAddclass

Jquery Problem Overview


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?

Jquery Solutions


Solution 1 - Jquery

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

Solution 2 - Jquery

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..)

Solution 3 - Jquery

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionCurtisView Question on Stackoverflow
Solution 1 - JqueryJonView Answer on Stackoverflow
Solution 2 - JqueryGabriele PetrioliView Answer on Stackoverflow
Solution 3 - JquerychrisMView Answer on Stackoverflow