Don't use css selectors for JS dom selecting
JavaScript performance comparison
Info
Using the class attribute for both CSS selectors & JS hooks is super lame. You should be able to edit CSS class names without worrying about whether some JS is depending on them.
IDs are useless when you need to select non-unique elements.
In lieu of a separate HTML attribute that behaves exactly like class, can I use data- attributes exclusively for JS hooks and leave class for CSS?
Preparation code
<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<div>
<a href="#">Foo</a>
<a href="#" class="styling-class" data-jshook="js-hook-class">Select me!</a>
<a href="#" class="styling-class" data-jshook="js-hook-class">Select me!</a>
<a href="#">Foo</a>
</div>
Preparation code output
Test runner
Warning! For accurate results, please disable Firebug before running the tests. (Why?)
Java applet disabled.
| Test | Ops/sec | |
|---|---|---|
jQuery + class |
|
pending… |
querySelectorAll + class |
|
pending… |
jQuery + data attribute |
|
pending… |
querySelectorAll + data attribute |
|
pending… |
You can edit these tests or add even more tests to this page by appending /edit to the URL.
0 comments