Is it bad form to use html class attribute as variable

I am wondering if the html class attribute should be used for styling only. Is there any downside to using a class attribute as a variable. The W3 spec http://www.w3.org/TR/html5/dom.html#classes doesn't point anyway, but all examples and a tutorial point towards styling just a few objects.

In my case, I want to use a class attribute as a variable that matches the key value in an array of objects. For example, in my Javascript code, I have an object that has multiple key / value pairs. In my web application, I have several save buttons. When the save button is clicked, I get the value of the parent class attribute and use it as a key for the object to find out which value to change. The class attribute of the parent has no other meaning than to tell me which key value pair will change in my object

+3


source to share


3 answers


While I'm sure it is possible to use classes in this way, that is certainly not their intended purpose. html has data attributes that provide the required functionality, for example

<button data-key="some value" name="" id="">click me</button>



Then you can get that value ( onClick

if you like) and use it as a key for the object / data structure. Theres a good review here

+6


source


While this is not bad, it is not best practice.

Instead of using a class attribute, you can define explicit data attributes. Using the class attribute means that you cannot use multiple classes (because that would be a weird key to search in an object, right?).

For example:



<div class="any classes you like" data-mykey="searchforthiskey">
  <button></button>
</div>

      

In jQuery:

$('button').click(function() {
  var key = $(this).closest('div').attr('data-mykey');
});

      

+3


source


From a functional point of view, there is no reason NOT to use a class attribute to store information about this element. You can access a class attribute as easily as you can access a data attribute.

From a standards standpoint, it is probably better to use the data attribute. What for? Well, if you are the only person working on your interface, it doesn't matter. If you are one of the many on the development team who work specifically on the JavaScript side, you may run into conflict with another third party developer who works on the HTML / CSS side. They can remove a class from an element without realizing that it is also being used as your javascript hook into that element. In this case, you'd be better off creating your own data attribute, which then makes it clear that this attribute is likely data-related, and won't be harassed by someone just trying to style that element.

+2


source







All Articles