What are the differences between using data-attributes and class / ID for javascript behaviour?

NT3RP picture NT3RP · Mar 19, 2013 · Viewed 7.2k times · Source

I have been working on an application, the front-end is primarily using jQuery.

We rely on certain classed elements being present on the page so that we can attach behaviour to them. For example:

$('.block').on('click', clickHandler);

One of the other developers said we ought to decouple presentation from logic (which I agree with). Because the classes are used for presentation, he suggested using data attributes:

$('[data-attribute-name~=value]').on('click', clickHandler);

However, I know the following about this approach:

  • It is significantly less performant than a class-based selector
  • HTML classes are used to impart semantic meaning to a DOM element, and, as such, are not restricted to presentational uses.

I don't see any particular mention of either when reading up on unobtrusive javascript.

What are the major differences of using [data-attribute] over classes / IDs?

Is it strictly a matter of performance / preference?

Answer

Steve picture Steve · Mar 19, 2013

Because the classes are used for presentation

This is only partly true. Classes are used for both, presentation AND behavior. There is nothing wrong with using classes for attaching behavior to multiple elements.

Data-attributes are great for carrying additional element specific information, but I would highly advice against using data-attributes for the sole purpose of attaching behavior.

If you REALLY need to separate the use of classes for presentation and behavior purposes, I would recommend you name them appropriately. For example, you could do:

<div class="pres-alert">Watch Out!</div>

vs.

<div class="behav-alert">Watch Out!</div>

or

<div class="pres-alert behav-alert">Watch Out!</div>

However, I find this overkill. I often find myself using the same classname for both, behavior AND presentation. In the end, behavior and presentation are often closely related.

UPDATE:

To take your co-developer's comment a little further, I believe (s)he is actually wrong to associate class attributes with presentation. The HTML5 specs for class attributes even state:

There are no additional restrictions on the tokens authors can use in the class attribute, but authors are encouraged to use values that describe the nature of the content, rather than values that describe the desired presentation of the content.

http://www.w3.org/html/wg/drafts/html/master/dom.html#classes

So rather than using class="big-red-box", you should use class="alert". Now, you can attach styles to that alert class (color:red;font-size:bold) as well as behavior (i.e. pop-up on hover).