It's been said that selecting an element by ID is faster than by class (although marginally, admittedly). The reasoning is that the browser only scans the document once until it runs into the ID - then it stops looking because, in theory, there shouldn't be another instance. If this were true, the second instance of an ID used in the markup shouldn't be styled at all.

However, as you can plainly test yourself, this is not the case. I've tried this in every modern browser, including IE7 and 8. The browser will render both elements with the same ID with the same style. This leaves me to question whether selecting by ID is, indeed, faster.

I understand that selecting by ID within Javascript is faster because I do think it stops looking for IDs after it hits the first one. But the same can't be said for style sheets. If anyone can shed some light on why people are claiming selecting by ID is faster (even if vanishingly so), I'd much appreciate it.

1 answer


Yes, using ID selectors is faster than class selectors because there's only one id style in a page. But difference is small and if you add another selector the benefit will be lost.

For example: #header li {...}

You can check out the test done on performance of selectors here:

*CSS reads from right to left: High Performance Websites Blog

Answered over 7 years ago by ariellephan
  • You say ID selectors are faster than classes because there's only one, but clearly all IDs that are repeated in the markup are being styled equally. The browser doesn't just stop at the first - so why is everyone saying there's an inherent performance gain? This has nothing to do with chained selectors. Samuel Ferrell over 7 years ago
  • If you repeat the ID then it defeats the purpose of using ID in the first place. You can check out the test done on performance of selectors here: ariellephan over 7 years ago