Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it better to use class selectors or custom attribute selectors with jquery?

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

like image 826
YakobeYak Avatar asked Nov 18 '10 12:11

YakobeYak


2 Answers

I would use class selectors. Using custom attribute selectors would be:

  1. Invalid HTML. HTML only permits certain named attributes to be present on certain types of elements.
  2. Slower. While jQuery can use native .getElementsByClassName in your first snippet, it can't for the second. This could lead to a slowdown in modern browsers.
like image 200
PleaseStand Avatar answered Oct 18 '22 18:10

PleaseStand


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.

like image 40
arena-ru Avatar answered Oct 18 '22 18:10

arena-ru