Question

I often need to select multiple elements at once with jquery... to do this I usually just add a class to all the elements I'd like to select and then use jquery to select by class.

Is this a bad practice or should I use something like the html 5 data attribute instead?

Was it helpful?

Solution

I think that w3 spec is helpful here:

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

The money quote:

Custom data attributes are intended to store custom data private to the page or application, for which there are no more appropriate attributes or elements.

It then goes on to use the example of a music site that uses data- to contain the length of music tracks, for sorting.

It would seem that data- are to be reserved for these types of uses vs classes/ids which are intended as selectors.

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

OTHER TIPS

I would say it's okay for a general reference where no arguments need to 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 multiple classes or "data classes", like class="flashing-15times onhoveronly", etc...

Once you need to start passing arguments or variables, you should move towards data attributes or other OOP methods.

It's excellent practice. It's what the class attribute is for. Always remember that the class attribute is part of the semantic layering of HTML, for flagging groups of objects with a common property, and not a part of CSS. It's the CSS selectors that provide the binding between the semantics of HTML and the presentation of CSS. And flagging groups of objects with a common property is exactly what you are doing.

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

This used to be the standard way to do it. However, the currently standard way to do it, is using data- attributes. For example, if you want to make a plugin that makes a certain element have a tooltip, you could 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));
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top