ob. ob. - 7 months ago 73
Javascript Question

jQuery .hasClass() vs .is()

is there a preferred method of determining whether an element is assigned a class, from a performance standpoint?

$('#foo').hasClass('bar');


or

$('#foo').is('.bar');

Answer

Update:

I committed a test following a comment and four upvotes to very comment. It turns out that what I had said is the correct answer. Here is the result:

enter image description here

http://jsperf.com/hasclass-vs-is-so


The is is multi-purpose, you can for example do is('.class'), is(':checked'), etc which means is has more to do where is hasClass is limited which only checks for a class being set or not.

Hence, hasClass should be faster if performance at any level is your priority.