jqueryperformanceaddclass

Should I use "hasClass" before "addClass"?


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?


Solution

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