Use date or class to query DOM elements

5

Here I am needing a little help to get a broader view on this.

As a rule I usually avoid using class to query elements in HTML, for this I end up using a custom data property .

In many cases I end up having duplicates in html:

<div data-content="" class="content" />

Where my CSS would look something like this:

.content { ... }

And to query this element in JS would do something like this:

var content = document.querySelectorAll("[data-content]");

My intention here is to keep the presentation layer separate from the behavior so that a change in page layout does not affect scripts and vice versa.

So I would like to hear the strengths and weaknesses of this approach? I even accept a JSPerf comparing querySelectorAll to getElementsByNameClass

    
asked by anonymous 04.03.2015 / 17:53

2 answers

1

Based on the principle we are looking for by attribute, I believe this is slower as it will check all elements of the page, which may have this attribute.

So searching for tag or making a seletor might be faster.

Recently I'm using custom data property. for dynamic attributes, this really makes manipulation of elements much easier regardless of behavior.

But I believe that a performance test can help to get that doubt for sure.

    
04.03.2015 / 21:29
1

In conceptual terms the answer does not have to be long.

If you use classe or even custom data property , the interpreter goes looking for element by element until you find all that hits your selector. That is, all elements of your document are parsed .

For custom data property , the situation is slower because in addition to analyzing the elements , the interpreter also analyzes all the properties of these elements.

If you have a certain behavior for a group and elements, I believe in terms of performance , using class is the most appropriate. In terms of readability I agree that property is much more robust to the eyes.

  

If your document is not so large, I think it's worth sacrificing   a bit of performance and use property . It will not affect   some milliseconds that will not result in anything very noticeable to your   end user.

    
04.03.2015 / 21:54