aspirinemaga
aspirinemaga

Reputation: 3947

jQuery selector speed performation

I have a big table list of products, which is dynamic and changes with ajax. There is a for about 100 rows in that table.

I saw already that a contextual method $('.className', '#parentElement'); of selecting elements performs much better than usual $('.className'); or $('#parentElement .className');. (correct me if wrong)

In some circumstances i need to select a specific element with jQuery, there are dynamically added unique id="product-name-123456" and class="mainproductOffer" to each new row.

So, what performs faster from these two methods ?

  1. $('tr[id^=product-name-]').click(function(){...});

  2. $('tr.mainproductOffer').click(function(){...});

or

Is there any other method doing the same thing faster ?

Upvotes: 1

Views: 127

Answers (4)

axel.michel
axel.michel

Reputation: 5774

In this case use the class selector, it is faster than the attribut selector. You should use event delegation - for example:

$('table').on('click','.mainproductOffer',function() {}); 

to reduce the number of event handlers. If the class (mainproductOffer) is only used for the TR tag, remove the Tag from the selector too.

Upvotes: 3

bipen
bipen

Reputation: 36551

$('tr.mainproductOffer').click(function(){.....; OR
$('table').on( 'click', 'tr.mainproductOffer', function(){...; 

are faster since

according to the jquery documentation

jQuery can process simple selectors of the form tag#id.class very quickly when they are used to filter delegated events. So, "#myForm", "a.external", and "button" are all fast selectors. Delegated events that use more complex selectors, particularly hierarchical ones, can be several times slower--although they are still fast enough for most applications. Hierarchical selectors can often be avoided simply by attaching the handler to a more appropriate point in the document. For example, instead of $("body").on("click", "#commentForm .addNew", addComment) use $("#commentForm").on("click", ".addNew", addComment).

Upvotes: 0

Sergii
Sergii

Reputation: 1320

So, what performs faster from these two methods ?

$('tr.mainproductOffer').click(function(){...});

Is there any other method doing the same thing faster ?

Unsurpassed article 'jQuery Anti-Patterns for Performance' would help you

Upvotes: 1

Akhil Sekharan
Akhil Sekharan

Reputation: 12693

  1. Use on() (event delegation), since its dynamically added.
  2. Class selector is faster than attribute selector

    $('tr').on( 'click', '.mainproductOffer', function(){...});

Upvotes: 0

Related Questions