I noticed that some of developers in our team are creating long jQuery selectors like:
'div.someclass > span.someotherclass ...'
I know, that jQuery will try to use native DOM methods for classes and tags, but I think if it would be more efficient to use something lite this:
'[data-gid="my-element-group"]'
instead of those long mixed class/tag selectors.
Will custom attribute selectors be faster than long class/tag selectors or it depends on circumstances? Which approach to choose for a Javascript-heavy website?
P.S. I guess, those long selectors are also dangerous if HTML designers and Javascript coders are working separately – designer may break Javascript functionality just by changing CSS classes or moving tags around. But if they see ids and data-gids, they can leave them alone, and that should be much safer… but will it sacrifice performance?
P.P.S. I don’t care about invalid HTML4 because of custom attributes, the performance is much more important for most of my clients.
The longer selectors should be faster. Here’s an example. Given the following HTML:
And the following jQuery:
Here’s the results from a quick test:
However, it’s worth noting that in the real world the difference is going to be minimal and you should use whichever suits you best.
You could make your
data-*selector slightly better (performance-wise) by making it more specific:But another quick test reveals (for me, in Chrome 15 at least) that the longer selectors still win.
I think in older browsers with no support for
querySelectorAll, the difference will be even more pronounced in favour of the longer selectors, which can use the nativegetElementsByTagName.