Aquazie
Aquazie

Reputation: 69

JQuery if() vs :contains

What is the more efficient way to write this:

if ($('.shipping .price').text() === "FREE"){ 
    $('.shipping .price').addClass('text-primary'); 
}

OR

$('.shipping .price:contains("FREE")').addClass('text-primary');

Upvotes: 5

Views: 612

Answers (1)

amoebe
amoebe

Reputation: 4992

A quick test shows that the code with if runs about 5 times faster than the one with the contains-selector. However, as others already explained in the comments, the two are not equivalent.

You could speed things up even more by caching the call to $('.shipping .price') like this:

var elem = $('.shipping .price');
if (elem.text() === "FREE"){ 
  elem.addClass('text-primary'); 
}

However, for almost every real-life scenario performance differences will not matter at all and you should go for the option that is more efficient to read for other humans. If you really care for performance (for example if you have a rather large price list) you should use vanilla JS wich is about another 10 times faster in this case.

Upvotes: 3

Related Questions