Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Semantically "correct" way to select multiple elements in jQuery?

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-*?

like image 451
RemarkLima Avatar asked Nov 23 '16 14:11

RemarkLima


2 Answers

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

  1. A blog post discussing your question
  2. W3C HTML4 attributes
  3. W3C HTML 5 data attribute
like image 70
FK82 Avatar answered Sep 24 '22 02:09

FK82


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.

like image 43
Barudar Avatar answered Sep 26 '22 02:09

Barudar