I was just wondering if there is a reason why I should prefer this
<div class="identifying-class">bla bla</div>
<div class="identifying-class">bla bla</div>
var interestingElements = $("div.identifying-class);
over this
<div data-identifying-attr="true">bla bla</div>
<div data-identifying-attr="true">bla bla</div>
var interestingElements = $("div[data-identifying-attr]");
Are attribute based selectors quicker /slower/the same speed as class based selectors?
Is one method deemed better practice than the other – if so why?
The class selector will be faster (in modern browsers with
getElementsByClassNameanyway, and quite likely in older ones too). Here’s the results of a quick test:Note that I’ve only run that on Chrome 15. Other browsers may differ slightly but the outcome should be similar. Also note that in the real world this is highly unlikely to make any difference to performance. The difference between the 2 is only 19% (despite the fact it looks like a big difference on the graph).