I can not say this quoting some author, but what I can say is that people will be happy if you do not use a class and I will justify.
In HTML5 we have the data-attributes
, He in my opinion are ideas for this type of solution, because they are in the scope of HTML, and not CSS. This will prevent anyone from searching the CSS for something that is not there. This technique has been widely used by various System Design Frameworks such as Bootstrap and Materializa for example, and other JS with jQuery plugin and components in general.
Here you can read about the data-attributes
: https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Using_data_attributes
For example look at the code of this Bootstrap button used to make a Collapse, see how it has several data-
(documentation link)
<button class="btn btn-primary" type="button" data-toggle="collapse" data-target="#collapseExample" aria-expanded="false" aria-controls="collapseExample">
Button with data-target
</button>
In JS you can access them with var atributo = element.getAttribute(nomeDoAtributo);
In addition, there are JS methods to work with such attributes as Element.getAttribute()
and make a dataset
The estate HTMLElement.dataset
allows access, in read and write mode, to all custom data attributes (date-*) in the element. It is a map of Domstring, with an entry for each custom data attribute.
Source: https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/dataset
In practice
Example of the use of dataset
. Look at the tag <button>
I have a data-nome=""
and a data-num=""
, and in the JS I call them with .dataset.nome
and .dataset.num
var btn = document.querySelector('button');
btn.addEventListener('click', () => {
console.log('oi "' + btn.dataset.nome+'"', 'e "' + btn.dataset.num + '" são...');
})
<button data-nome="meu nome" data-num="meu numero">clique aqui!</button>
In jQuery you can select them as
<div data-id></div>
$( "div" ).attr("data-id")
Tb is worth knowing about the .data()
available on jQuery https://api.jquery.com/data/
<div data-role="page"></div>
$( "div" ).data( "role" ) === "page";
My tip is to avoid as much as possible a CSS class just to be used as a selector in JS. This will make the code confusing, poor maintenance and inaccurate. I do not believe it is a good Pattern design
Thank you very much, Hugo! Sanou my doubt completely!
– Vinícius Alves
@I’m a designer, not a dev. and whenever I see classes used for this purpose I do not agree, harms the work, makes it difficult to maintain and understand. Having Data doesn’t make sense to use a css class as a JS selector. Read the links have things that can open your mind even more! Abs [] s
– hugocsl