-2

If you have html and throughout you have span elements like this:

<span id="element-1" class="elements"></span>
<span id="element-2" class="elements"></span>
<span id="element-3" class="elements"></span>

What is faster to find them:

$('.elements')

or

$('[id^="element-"]')
capvidel
  • 359
  • 3
  • 14
  • IMO, `class` selectors as other is based on `attribute selectors` – Rayon Jun 01 '16 at 11:42
  • ID, is always faster, there should be only one. Oh, I see..hmm, yeah I have to agree with Rayon, an attribute selector is crappy. – zer00ne Jun 01 '16 at 11:51

5 Answers5

2

I don't think speed is a concern here, the difference between them is so quick it wont effect your code..

TeT Psy
  • 341
  • 3
  • 7
0

I think, id selector works faster.

HTML ID attributes are unique in every page and even older browsers can locate a single element very quickly.

Hiren Makwana
  • 1,976
  • 2
  • 13
  • 28
0

Id is obviously faster then class because there can be only one Id, once found need no more search. However the speed is not concern. If you need to do some work on multiple elements you use class but if you need to do work on a particular element you use Id.

suman
  • 728
  • 3
  • 10
  • 29
0

Id's in html are auto assigned in JS.

Because there can be only 1 id on the page with that name. the entire element is assigned into a JS variable.

For example: the element <span id='spanTagOne'>Text</span> will be a JS variable spanTagOne.

So you don't even need to get them since they are already assigned.

Hulke
  • 847
  • 5
  • 22
0

try this way to find

$('parent').find('.child') is a faster way to find element.

Abhay Yadav
  • 25
  • 10