Reputation: 497
I have some elements that should have both some data saved in them, and some styles applied.
Lets say i have a grid 4 x 4, like so:
I need to store the coordinates of each cell and use them via javascript, but also be able to style them individually.
I know i can save the data in the class itself like so:
<div class="cell row-3 col-3"></div>
and parse them in the js
I also know i can style cells in the css:
.grid .cell[data-row="3"][data-col="3"]{...some style...}
Both these approaches however are slower than the alternatives (get the data from data attributes and style with classes) i suppose.
So which one is more effective? Or which one is best in what situations?
I guess i can include both classes and data in the elements (like in the fiddle), but is this the best approach?
Upvotes: 0
Views: 150
Reputation: 92893
I would lean toward using data, simply because the class
has multiple values and must either be parsed or matched.
Furthermore, your approach toward using classes amounts to a hack. You are storing data; why shouldn't you use data attributes?
As a plus, data-
attributes are just a new kind of HTML attribute, and you should be able to manipulate them even if the browser doesn't support HTML5 (albeit with a bit more work).
Finally, libraries (frameworks, whatever) like jQuery have built-in methods for reading data-
attributes, which (if you were to use them in the future) would simplify your code immensely.
There's nothing wrong with using classes the way you have done; it's just not necessary. Data tags are more appropriate, more clear, and easier to manipulate.
Upvotes: 2