This is because $("#id") internally uses the built-in document.getElementById function, which uses a map that associates an identifier with a (unique) element that has that identifier.
Here is the corresponding code in jQuery source:
// Easily-parseable/retrievable ID or TAG or CLASS selectors rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/ ... // Speed-up: Sizzle("#ID") if ( (m = match[1]) ) { if ( nodeType === 9 ) { elem = context.getElementById( m ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document
You will notice that:
- it is used when the regexp detects the form
#someId - any provided context only adds a test and does not speed up its execution
Note that this rule is still true outside of jQuery when you define CSS rules or use document.querySelector : when you know the identifier, there is nothing faster than using document.getElementById (except for the cached element ...).
source share