I have read that it is better to select using "id" than "class" with jquery. However, say i have several divs on a page that i need to select with jquery and perform the same manipulation. I cannot select with the "id" attribute because it would nolonger be unique. eg:
<div id="selectMeOnClick">
...
</div>
<div id="selectMeOnClick">
...
</div>
... many more divs ...
which leaves me (i think?) with 2 alternatives:
Use class selectors
<div class="selectMeOnClick">
...
</div>
Use custom attribute selectors
<div data-select="selectMeOnClick">
...
</div>
My question is: Are these really the 2 alternatives left? And what is the most efficient solution?
Thanks
I would use class selectors. Using custom attribute selectors would be:
.getElementsByClassName
in your first snippet, it can't for the second. This could lead to a slowdown in modern browsers.Yes, it is better to use "id" than "class" with jquery. But not only with jquery. This is general approach.
In your situation you have to provide more information. If you want to select several divs with same class - may be all of them are child of other div, e.t.c. And you can get them as a child of some div which you can get by id.
You have to create such DOM structure that you can access to elements by id or logically by some properties.
Also, if you want to change some css attribute in exact css-class, it is not the worst idea to get div's by class.
Also custom attribute selections not good way. It is not valid.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With