5
Here I am needing a little help to get a broader view on this subject.
As a rule I usually avoid using class
to query elements in HTML, I end up using a custom data property
.
in many cases I end up with duplicates in html:
<div data-content="" class="content" />
where my CSS would be something like this:
.content { ... }
And to consult this element in JS would do something like this:
var content = document.querySelectorAll("[data-content]");
My purpose here is to keep the presentation layer separate from the behavior layer, so that a change in the layout of the page does not affect the scripts and vice versa.
So would you like to hear the positive and negative points of this approach? I even accept a Jsperf comparing querySelectorAll
with the getElementsByNameClass
Are you assuming that
class
only refers to the corresponding CSS class? In fact no, the classes serve to complement the semantics of the elements, and group them into sets with common characteristics. Starting from this concept, it is totally valid to use classes as selectors also in JS.– bfavaretto
By no means is it more a matter of style of convenience than of limitation.
– Tobias Mesquita
Just to complement, the W3C specification itself makes it clear that class is not limited to style only, I just find it inconvenient to mix 'style' with 'behavior'. Note: Assigning classes to an element affects class matching in selectors in CSS, the getElementsByClassName() method in the DOM, and other such Features. There are no Additional Restrictions on the tokens Authors can use in the class attribute, but Authors are encouraged to use values that describe the Nature of the content, rather than values that describe the desired Presentation of the content.
– Tobias Mesquita