Reputation: 57
I have a dynamically constructed table built from data returned from an AJAX call. At the end of the function that builds the table, I need to apply jQuery UI wrappers to some anchor elements in the table, identified by icons of "map-marker" and "th-list". Which of these two options is better optimized?
$("#tblResults tbody tr td").find("a[data-icon='map-marker'], a[data-icon='th-list']").button();
or
$("#tblResults tbody tr td a[data-icon='map-marker'], #tblResults tbody tr td a[data-icon='th-list']").button()
This particular example won't suffer from doing it the less efficient way, but I have other places in my code where I'm applying callback functions to significantly larger tables, and it might make a difference there.
Upvotes: 1
Views: 44
Reputation: 34168
For reference see here: https://stackoverflow.com/a/16423239/125981 Now that is not an exact duplicate of your question but will help explain your question as a supplement.
The second is not better because it will do all this (I describe) twice so no not that one. Now how to actually improve the first one...
Since you mentioned "multiple" let's first get a reference to your table, then cache that in a variable to avoid multiple DOM hits just to do that.
let myResultsThing = $('#tblResults');
Now we have the element referenced by the ID (which is the fastest selector)
Why? Let's talk about that. The Sizzle engine that is in use here uses a right to left selector so, what this $("#tblResults tbody tr td")
says is 1. Find all td
, 2. filter those td
for those inside a tr
, 3. Filter those for those inside a tbody
4. Filter those that fall within the element denoted by the id #tblResults
Now if you have 10 tables with 100 td
each in 10 rows in three tbody
each you can see this is quite a busy amount of work. So by isolating to the ID first, we would eliminate very quickly 90%+ of our effort here.
OK, we have our table reference way up there above. Using that we can find the tbody
(or all the tbody
to be more precise there may be multiple), thus eliminating any td
in headers and footers.
let myTbodies = myResultsThing.find('tbody')
//get into the rest of it
.find('tr td').find("a[data-icon='map-marker'], a[data-icon='th-list']").button();
Now here I might be inclined to actually test all that above against
myResultsThing.find("a[data-icon='map-marker'], a[data-icon='th-list']").button();
Depending on what exactly your DOM looks like, you might cache (as I did the table) clear down to the TD or A element selectors but I will leave that to you as an exercise since we have no markup to speculate against here.
Upvotes: 1