Should I use “hasClass” before “addClass”? [duplicate]

雨燕双飞 提交于 2019-11-27 10:55:45

问题


This question already has an answer here:

  • Check if class already assigned before adding 4 answers

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?


回答1:


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




回答2:


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




回答3:


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.



来源:https://stackoverflow.com/questions/13358887/should-i-use-hasclass-before-addclass

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!