I often use classes
as a means to identify a related set of elements, for example:
<input value="10" class="sum-this" />
<input value="20" class="sum-this" />
<input value="30" class="sum-this" />
The sum-this
class has no CSS, and isn't defined in any CSS files -it's simply used in some jQuery - for example:
var total = 0;
$(".sum-this").each(function(i, el){
total += parseInt($(el).val());
});
console.log(total); // 60?
Is there a correct way to do this? Should I use another attribute? rel
or data-*
?
As @Pointy and @JustinPowell have stated in the comments, this is completely valid. In fact, it's also explicitely stated in the W3C HTML4 specification that using class
attributes for purposes other than selecting style is completely valid. I quote:
The class attribute, on the other hand, assigns one or more class names to an element; the element may be said to belong to these classes. A class name may be shared by several element instances. 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.
However, HTML5 also added the custom data-*
attributes (where *
is a custom string) for this purpose.
LINKS
As said in the comments, it's perfectly fine to use classes in the JavaScript only. But here's a suggestion: when my colleagues want to use a class for this purpose only, they prefix it by 'js-'
in order to distinguish classes used for styling from classes made for JS.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With