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?
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.
Locating elements by id is faster than css. Because : id of an elements is more specific than css of an element.
The ID selector #first has priority over the class and tag selectors.
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.
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.
I don't think you should be really that concerned : selecting by id
and selection by class
just don't have the same meaning :
id
class
.
Still, here's a benchmark that could interest you : Speed/validity selectors test for frameworks.
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