Example, if I have an unordered list lets say,
<ul>
<li class="foo">Foo</li>
<li class="bar">Bar</li>
</ul>
I can select foo as $('ul li.foo'), $('li.foo') or $('.foo').
Then which way is more efficient (if any) and why. Or is it that specifying parents while selecting children is only for the sole reason to remove any conflict in case there are other elements having same class name!
The simple class selector
.foowill be fastest in modern browsers, because it can use the nativegetElementsByClassNamewhere available.Here’s a benchmark showing exactly that:
You can run that performance test in all the browsers that matter to you, and make a decision based on the results. Or just use the selector that works best for your situation, since in the real world it’s going to make no noticeable difference whatsoever.
Update
Now that we can see the performance results from a wider selection of browsers, you can see the difference between old and new (lack of
getElementsByClassNamein IE7 and 8). However, you are likely these days to receive significantly more traffic from newer browsers, but I don’t know your site, so as I mentioned previously, you just need to pick what works for you. If for whatever reason 90% of your traffic comes from IE7, you should probably useli.foo.