In jQuery whenever I encounter something like this:
$("div#MyDiv").....
I generally say to the developer: “Don’t bother putting the div in front of #MyDiv, ID selectors are the fastest.” I.e.
$("#MyDiv")....
This is because the latter will hook directly into document.getElementById rather than having to scan the DOM for all <div> elements first.
My question is, do the same rules apply to CSS selectors? I.e. rather than:
div#MyDiv
{
}
Is it faster to have simply?:
#MyDiv
{
}
(I realise that CSS selectors are incredibly fast anyway, so in reality neither would make a significant difference.)
Many Thanks
EDIT
Any links, or references might be useful for the purposes of this discussion. Thanks 🙂
I’d say that it’s extremely unlikely that it makes any real-world difference. In theory, yes, there’s one fewer check required (because
div#fooreally does need to be adivto match the selector, according to the spec). But the odds of it making any real difference in a real-world browser app? Near zero.That said, I always cringe when I see things like
div#fooin HTML applications. HTML has only one ID-type attribute (id), so there’s no need for the further qualification. You make the CSS selector engine (either the browser’s or jQuery’s) work harder to figure out what you mean, you make the selector fragile (if thedivbecomes afooter, for instance), etc., and of course you do leave yourself open to a stoopid selector implementation that fails to recognize that it can look something up by ID and then check to see if it’s adivand so goes looking through all thedivs. (Does such an implementation exist? Possibly, you never know.) Barring some edge cases, it always makes me think someone doesn’t quite know what they’re doing.So for me, speed isn’t the main argument. Pointlessness is. 😉