Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery: What's the difference between referencing an element using #[objectId] or [id=objectId]

Can anybody tell me what's the difference between referencing an element using
#[objectId] or [id=objectId]?

like image 946
pestacio Avatar asked Feb 14 '23 19:02

pestacio


1 Answers

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.

like image 83
Denys Séguret Avatar answered Feb 17 '23 07:02

Denys Séguret