Should I use "hasClass" before "addClass"?

<>

This question already has an answer here:

Answers


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


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


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.


Need Your Help

How to verify if a String in Java is a valid URL

java url

How can I check if a string is a URL in Java?

How to safely open/close files in python 2.4

python file io

I'm currently writing a small script for use on one of our servers using Python. The server only has Python 2.4.4 installed.