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

5

16

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?

Univalve answered 19/3, 2013 at 18:15 Comment(5)
IDs can also be used to impart semantic meaning to a DOM element.Comeon
Unique IDs are always the fastest way to locate an element, followed (as I understand it) by tag selection, class selection, and arbitrary attribute selection. In practice, the user will rarely notice any difference unless the page is particularly large.Brassica
The only major difference would be performance when selecting by only class vs by data attribute, though that wouldn't impact modern browsers enough to matter.Storekeeper
That classes are used to target elements for styling doesn't mean that classes would be part of the presentation layer. There's nothing wrong with using classes to classify elements for non-styling purposes.Extortion
Take a look to this article: roytomeij.com/2012/…Persse
R
13

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).

Rejoice answered 19/3, 2013 at 18:20 Comment(3)
By "pure purpose of attaching behavior" you mean using data-attributes as criteria for selectors, right?Boarder
To put it another way: classes (i.e. the class attribute) can be used for any sort of classification, be it presentation, behavior, or anything else. There are no rules or restrictions; you're free to use them however you like. Given such freedom, there is no reason to use custom data attributes to group related elements (especially for use with selectors) when you have a built-in, tried and tested attribute that's dedicated to that purpose.Sauls
Using the same class for both behavior and presentation is going to come back and bite you at some point. Eventually, you are going to find you want to apply the same behavior to an element that needs to be styled differently, at which point you are either going to be stripping away styling to keep the listener pure, or adding a new class to the listener. Using a data attr for listeners - especially when applied consistently - can make your code significantly more manageable long term. See alexkinnee.com/2013/11/… for a bit more detail.Stodder
Y
3

You should definitely stick with IDs when you can if for no other reason than it is the fastest of the selectors. I would expand more on your second point: HTML classes should only be used to impart semantic meaning to a DOM element. That is using a CSS class that I assume you have above like:

.block {
    display: block;
}

actually goes against the spirit of HTML/CSS. That's not to say we don't all do it, but the point is that you should at least have semantic meaning behind the class names that you want to bind to:

$(".show-popup").on('click', showPopup);

As per your specific question, "what are the major differences:" as you say, using the class is faster / more performant. The syntax is certainly cleaner. The spec doesn't seem to say anything specific about using the data- attributes as selectors. However, I've always interpreted the data- attributes as being designed to store scalar data whose values are used for algorithms. This means that values can change frequently and data may be added to/removed from elements frequently which would make them unideal for selectors.

Yamamoto answered 19/3, 2013 at 18:25 Comment(0)
S
2

You can have multiple classes and you can associate the name of some with the logic and others with presentation and keep the performance of class selector.

<el class="block logicClass" /> 
Shrink answered 19/3, 2013 at 18:19 Comment(0)
J
1

A class can be associated with multiple elements whereas an id is associated with only one element.

I just read your question a little more carefully and see that you need more information:

I personally use data attributes to store necessary variables that can be used when processing an event and I use the class "event" for anything that will be used by jQuery rather than CSS. For Example:

<a class="event" data-action="Alert" data-id="123" href="#">Foo</a>

<script>

var Event = {
  Alert: function(ele){
     alert(ele.attr("data-id")); //alerts "123"
  };
};

$(".event").on("click",function(){
   var ele = $(this);
   Event[ele.attr("data-action")](ele);
});

</script>

Hope that helps!

Joppa answered 19/3, 2013 at 18:16 Comment(3)
This answers the the question posed by the title, but it's not the actual question being asked.Chatav
Apologies: I noticed as soon as answers started rolling in that I missed a key word in the title. I have since updated the question and title.Univalve
I realized that soon after answering and updated my answer. Thanks.Joppa
B
1

Data-Attributes are not intended only for selectors. Sometimes you want to give an extra meaning to a tag that script may use.

For example you could have a data-attribute-validate-repeat="firstpassword" on a password-repeat field, where the value refers to to the first password. Then a form-validator can read this attribute to find the other field by ID. This cannot be done by just classes and ID's unless you use a special naming convention, which would not be very neat.

Boarder answered 19/3, 2013 at 18:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.