Search code examples
htmlclass-attribute

Is it bad practice to use the html class attribute as a javascript handle


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?


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