Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

id vs class selection benchmark

Has anybody bench marked selecting elements with id's and class's from CSS and javascript?

It would make sense that an element with an id is faster to select than if it had a class even if it was the only element with that class.

Do I really need to be concerned?

like image 239
zaf Avatar asked Apr 01 '10 11:04

zaf


People also ask

Which is better ID selector or class selector?

You should use a class if you need to use the same selector more than once within a page or a site. While an ID is specific to a single element, classes can be assigned to multiple elements on a page or throughout the website. They are not unique.

Which selector is faster ID or class?

Locating elements by id is faster than css. Because : id of an elements is more specific than css of an element.

Which has more precedence ID or class?

The ID selector #first has priority over the class and tag selectors.

What is stronger ID or class?

ID's are more specific than classes and take precedence over them. This is because ID's have to be UNIQUE on every page...so they are by nature very specific. Classes can appear multiple times.


2 Answers

When searching for an id, the selector will halt as soon as it's found a match (even if there are many) - I assume there's some sort of key/value lookup table for this purpose, as it's much faster than DOM traversal. Here's why, and here's an excerpt:

It's still much better to select by ID...because jQuery uses the browser's native method (getElementByID) to do this and doesn't have to do any of it's own DOM traversal, which is much faster.

The linked results there show >100x speed improvement with id vs class.

When searching for a class, the entire DOM (or scope) is searched. Here's a benchmark using scope.

You can benchmark selectors in your own browser here.

like image 166
Andy Avatar answered Oct 04 '22 21:10

Andy


I don't think you should be really that concerned : selecting by id and selection by class just don't have the same meaning :

  • If you want to select an element, knowing how to uniquely identify it, use it's id
  • If you want to select one or many elements, knowing there might be more than one, note having a way to uniquely identify it/them, use the class.


Still, here's a benchmark that could interest you : Speed/validity selectors test for frameworks.

like image 28
Pascal MARTIN Avatar answered Oct 04 '22 21:10

Pascal MARTIN