Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

450
Views
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');
over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

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.

over 4 years ago · Santiago Trujillo Report

0

Since is is more generic than hasClass and uses filter to process the provided expression, it seems likely that hasClass is faster.

I ran the following code from the Firebug console:

function usingIs() {
for (var i=0; i<10000;i++) {
 $('div#example-0').is('.test');
}
}

function usingHas(){
for (var i=0; i<10000;i++) {
 $('div#example-0').hasClass('test');
}
}

usingIs();
usingHas();

I got:

  • usingIs: 3191.663ms
  • usingHas: 2362.523ms

Not a huge difference, but may be relevant if you're doing lots of testing.

EDIT when I say 'not a huge difference, my point is that you need to do 10000 cycles in order to see 0.8s of a difference. I'd be surprised to see a web application such that switching from is to hasClass would see a significant improvement in over all performance. However, I grant that this is a 35% improvement in speed.

over 4 years ago · Santiago Trujillo Report

0

Both should be pretty close in terms of performance but $('#foo').hasClass('bar'); seems more readable and semantically correct to me.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!