I've seen many examples(including favorite Twitter's bootstrap) where various APIs make use of $("[data-something]")
rather than selecting by class $(".something")
Nethertheless I tried to find information about performance between these two different selectors. I was surprised that many performance test did find out that those selectors are equally fast on most of the modern browsers so I decided to do my own test
I'm really confused right now and I don't know if it's my test that are done wrong(somehow?) or is it other tests that I inspected before?
Could anybody provide more information if I'm doing something wrong while testing or are these test correct and data-attribute selector IS in fact pretty much slower than regular class selector?
Thank you
A "flatter" DOM also helps improve selector performance, as the selector engine has fewer layers to traverse when looking for an element. Beginning your selector with an ID is a safe bet. With the first approach, jQuery queries the DOM using document.querySelectorAll ().
It’s the fastest and the best way to select the element because it directly maps to the element. jQuery is a library written on top of JavaScript, which means that it internally calls the JavaScript functions to do the job. When you use ID as a selector in jQuery, it internally calls document.getElementById ().
Pseudo selectors are useful for selecting elements with different states, or a particular element from a set of elements, but they are slower compared to other jQuery selectors. You should either find a way to replace the pseudo selector or be very specific in using it.
Beginning your selector with an ID is a safe bet. With the first approach, jQuery queries the DOM using document.querySelectorAll (). With the second, jQuery uses document.getElementById (), which is faster, although the speed improvement may be diminished by the subsequent call to .find ().
When using attribute selectors, performance may vary depending on querySelector support in your browser. jQuery will fall back to a built-in library (called SizzleJS) which is a lot slower.
Selection on class names will be faster because it will always use getElementsByClassName which is commonly supported on all common browsers.
The way I see it, classes serve a different purpose then data attributes. Classes will "categorize" elements so they can be styled properly and create structure.
Data attributes are exactly that: data. Sometimes you need to store additional data in your elements. For instance:
<table>
<tr data-id="4" data-category="1">
<td>Name</td>
<td>Email</td>
</tr>
</table>
Note that I'm not using the regular "id" attribute because of the same reason.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With