Can anybody tell me what's the difference between referencing an element using #[objectId]
or [id=objectId]
?
The first one is very fast, as jQuery internally uses getElementById
when it recognizes the pattern (using a regular expression).
The second one asks jQuery to iterate over all objects having an id. It's very slow. jQuery doesn't even stop iterating when it find one match in that case.
The only legitimate reason to use a [id...
selector is when you don't just search by an exact id, for example you might want to search all elements whose id starts with "something"
using $('[id^=something]')
.
Assuming you have a valid HTML (no reused id) and a valid id, you can still have problems with $('#'+someId)
(for example when your id contains a quote, or anything that breaks Sizzle's pattern recognition system). In that case, use $(document.getElementById(someId))
.
Following your comment : Yes, a "@"
in an ID makes it impossible for Sizzle (jQuery's selector engine) to understand your selector. Sizzle uses the following regex :
rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,
and /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/.test('#som@thing')
returns false
.
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