Reputation: 259
I need to do quite a few HTML manipulation using jQuery on a site where there are hundreds of products displayed in the same structures. Pretty much the blocks of codes are each individually wrapped in a div container with an identical class name.
Now I am wondering if I should insert an unique ID to the class name so I can use $('#ID') instead of $('.class') for HTML manipulation. Getting the idea from this article #3.
I will probably use a for loop to insert an id after the class to create the IDs. Is this worth the time? More importantly is it going to help the performance?
Edit: For the type of manipulation I am going to do, for loops will be used quite often for sure. Also, I am not quite sure if pagination means anything to the performance at all. Now the products are displayed 10 per page, the user has options to see more per page.
Upvotes: 1
Views: 60
Reputation: 5225
It's probably good practice to do it that way, but you will only notice the difference if your page is large (has many elements) or if you are selecting elements many times (i.e. inside a loop)
Its better and easier to sellect the element you need out of the cycle and use a reference to it inside
var obj = $('#someid');
while (expression){obj.something();}
Upvotes: 0
Reputation: 34012
Yes, ID selectors are much more efficient. Use them to narrow down your scope, and then you can select by class later on. Also, save selections that might be reused.
var container = $("#someId");
var products = container.find(".product");
//later on...
products.find(".class").doSomething();
Also, keep in mind that .children()
is more efficient than .find()
- so use that when possible.
Upvotes: 1