Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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');
like image 349
Aquazie Avatar asked Oct 18 '22 09:10

Aquazie


1 Answers

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.

like image 72
amoebe Avatar answered Oct 21 '22 06:10

amoebe