Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it bad practice to use the html class attribute as a javascript handle

I often need to select multiple elements at once with jquery... to do this I usually just add a class to all the elements I'd like to select and then use jquery to select by class.

Is this a bad practice or should I use something like the html 5 data attribute instead?

like image 370
RayLoveless Avatar asked Sep 05 '12 17:09

RayLoveless


2 Answers

I would say it's okay for a general reference where no arguments need to be passed.

i.e. All .flashing elements will have a flash effect applied to it. The end.

It gets out of hand when you start using multiple classes or "data classes", like class="flashing-15times onhoveronly", etc...

Once you need to start passing arguments or variables, you should move towards data attributes or other OOP methods.

like image 123
Steve Robbins Avatar answered Sep 21 '22 23:09

Steve Robbins


It's excellent practice. It's what the class attribute is for. Always remember that the class attribute is part of the semantic layering of HTML, for flagging groups of objects with a common property, and not a part of CSS. It's the CSS selectors that provide the binding between the semantics of HTML and the presentation of CSS. And flagging groups of objects with a common property is exactly what you are doing.

Just make sure that you use a meaningful name for the collection of objects you want to gather together to apply your jquery action to.

like image 35
Alohci Avatar answered Sep 21 '22 23:09

Alohci