Don't use css selectors for JS dom selecting

JavaScript performance comparison

Test case created by Ben Smithett

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.

Testing in unknown unknown
Test Ops/sec
jQuery + class
$('.styling-class').addClass('state-class');
pending…
querySelectorAll + class
var els = document.querySelectorAll('.styling-class');
$.each(els, function(index, el) {
  el.classList.add('state-class');
});
pending…
jQuery + data attribute
$('[data-jshook=js-hook-class]').addClass('state-class');
pending…
querySelectorAll + data attribute
var els = document.querySelectorAll('[data-jshook=js-hook-class]');
$.each(els, function(index, el) {
  el.classList.add('state-class');
});
pending…

You can edit these tests or add even more tests to this page by appending /edit to the URL.

Compare results of other browsers

0 comments

Add a comment