Should I use "hasClass" before "addClass"?

Curt picture Curt · Nov 13, 2012 · Viewed 26.3k times · Source

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?

Answer

Jon picture Jon · Nov 13, 2012

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