Bad practice using html class attribute as JavaScript handle

I often need to select multiple elements at once using jquery ... for this, I usually add a class to all the elements that I would like to select, and then use jquery to select by class.

Is this bad practice or should I use something like an html 5 data attribute?

+7
source share
4 answers

I think w3 spec is useful here:

http://www.w3.org/TR/2011/WD-html5-20110525/elements.html#embedding-custom-non-visible-data-with-the-data-attributes

Quote:

User data attributes are intended to store confidential user data of a page or application for which there are no more suitable attributes or elements.

He then uses an example music site that uses data to contain the length of the music tracks for sorting.

It would seem that data should be reserved for these types of use vs classes / ids, which are intended as a selector.

Here is another useful article to think about the subject: http://danwebb.net/2010/1/27/put-that-data-attribute-away-son-you-might-hurt-someone

+2
source

I would say that this is normal for a generic link where arguments should not be passed.

i.e. All .flashing elements will have a flash effect applied to it. The end.

It gets out of hand when you start using several classes or "data classes", for example class="flashing-15times onhoveronly" , etc.

As soon as you need to start passing arguments or variables, you should move on to data attributes or other OOP methods.

+6
source

This is a great practice. This is what is for the class attribute. Always remember that a class attribute is part of the semantic layer of HTML, in order to mark groups of objects with a common property, and not part of CSS. These are CSS selectors that provide a binding between the semantics of HTML and the presentation of CSS. And the checkboxes of groups of objects with a common property is exactly what you are doing.

Just make sure you use a meaningful name for the collection of objects you want to put together to apply the jquery action to.

+3
source

This was the standard way to do this. However, for now, the standard way to do this is to use data attributes. For example, if you want to create a plugin in which a certain element has a tooltip, you can do

 <div data-tooltip="This is a div"></div> 

You can select elements with a data attribute using the jquery hass attribute selector.

 $("[data-tooltip]").each(function(){ generate_tooltip($(this)); }); 
+2
source

All Articles