Best practice: class or data attribute as identifier
If you merely want to associate "values" to DOM elements for computational purposes then data-attribute
is the way to go since,
anything that is "data-" will be treated as a storage area for private data (private in the sense that the end user can’t see it – it doesn't affect layout or presentation)
Also, jQuery provides the .data(), which makes life easier so you don't have the trouble of using the [data-*]
selector.
If you are providing a class name then, considering semantics, it should have some style associated with it.
John Resig has written about data-attributes
Best way to test these things is to search for a test suite on jsperf.com
Here is the one you are interested in: http://jsperf.com/id-vs-class-vs-data-attribute
The most efficient selector is to use classes.
This is probably a consequence of classes being used more for selection, so browsers will optimize that more?
According to W3C
data-*
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. These attributes are not intended for use by software that is independent of the site that uses the attributes.
class
The class attribute has several roles in HTML: As a style sheet selector (when an author wishes to assign style information to a set of elements). For general purpose processing by user agents.
The bold text above is the autoritative assurance that it is ok to use class attribute without its definition in CSS. The warnings from VS 2012 about that are overzealous.
If you use class
attribute, you can benefit from native getElementsByClassName
searching (with O(1) time complexity) and classList
object for toggling, adding and removing class. There's nothing like There is relatively slower getElementsByAttributeValue
.Element.querySelectorAll('[data-attr="value"]')
ref See Oliver Moran's comment. It has O(n) time complexity.
On the other hand, if you need to store multiple data, you can use dataset attribute. So if you want searching or if the data affect the look of the element, I would use class
. If you need to store multiple data, the data
would be more appropriate.
In your particular case I would consider required
or pattern
input attribute (since HTML5 most of input validation moved from JS to HTML). To style such elements, CSS selectors use the same syntax as querySelectorAll
.