1

There are a group of similar elements with similiar IDs

Here are two ways to using Jquery to select them:

  1. ID + Regex (Example: How can I select an element by ID with jQuery using regex?)

  2. Add a redundant class to all the elements, then select the class

Here is the example:

http://jsfiddle.net/J6hGx/31/

Which approach is better? Is ID+Regex more time-consuming?

Community
  • 1
  • 1
James King
  • 1,574
  • 4
  • 19
  • 28
  • RegEx is not a natively supported selector. So it would be faster if you use classes to group similar elements. – t.niese Jan 12 '14 at 20:34
  • Is this really a performance bottleneck ? – Raphaël Althaus Jan 12 '14 at 20:35
  • @t.niese Sure but this class is **redundant**. – James King Jan 12 '14 at 20:36
  • @RaphaëlAlthaus No. I just want to know which approach is better? – James King Jan 12 '14 at 20:36
  • It's not a regex, that is the "attribute starts with" selector, that does have a "regex like" syntax. – adeneo Jan 12 '14 at 20:36
  • So I would go for redundancy : same elements with same behavior makes things clear for every reader. But that's just a point of view... – Raphaël Althaus Jan 12 '14 at 20:39
  • @adeneo You mean this?http://www.w3schools.com/cssref/sel_attr_begin.asp But this is CSS3 which is still under development. – James King Jan 12 '14 at 20:42
  • No, I mean [**this**](http://api.jquery.com/attribute-starts-with-selector/), which is what you're using in the fiddle, I'm just saying it's not a selector that accepts regular expression, it's a specific selector called *"the attribute starts with selector"*, it's not regex. – adeneo Jan 12 '14 at 20:47

1 Answers1

0

You will get better performance using classes than selectors.

In the DOM, whatever has more specificity will be better. Having unused classes does not frustrate the rendering engine.

Finally, using specific classes increases readability of the code.

beautifulcoder
  • 10,832
  • 3
  • 19
  • 29
  • This is wrong, classes are selectors in this context, and specificity has nothing to do with javascript performance. Wether or not the selector can be used directly by native methods or in querySelector is important, and in older browsers, classes are shite for performance as IE didn't support getElementsByClassName or querySelectorAll until recently (IE8 for QSA). – adeneo Jan 12 '14 at 20:50
  • You are right. But would the DOM API have an easier time querying by `getElementsByClassName` versus `querySelectorAll`? – beautifulcoder Jan 13 '14 at 01:31
  • No, not really, but in IE7 and below there's no option for classes at all, so jQuery has to iterate over all the elements in the DOM and check the className for each element, so in those browsers just about anything would be faster, but targeting by attribute does somewhat the same if queryselector isn't supported, so it would be the same thing. – adeneo Jan 13 '14 at 06:03