I’m currently reading up on jQuery to fill some gaps in knowledge.
Looking at the various CSS selectors, I see:-
-
#C(any element with an ID of C)$('#profile') -
E#C(any element of type E with an ID of #C).$('div#profile')
I know specificity is a big deal in the application of CSS rules, but given that it is bad practice to have duplicate IDs on a page, I’m wondering why the second form exists and how it is treated in jQuery.
Does it confer a performance advantage when interrogating the DOM? ( i.e. immediately limiting the scope of the selection ). This question applies mostly to jQuery, but I’d also be interested to know if it had any bearing on rendering engines, etc.
jQuery has a specialized “fast path” to handle selectors of the form
#Cwith a directdocument.getElementById. Selectors of the formE#Care not handled by this path and are instead delegated to the Sizzle library.Therefore I don’t see how
E#Ccould offer any performance benefit in practice, while there’s no argument for better performance in theory as well. Indeed,E#Cis much slower; see the massive performance difference here¹.That said, the
E#Cselector is of course more restrictive so the behavior of the two will be different no matter if the selection is done by jQuery or any other medium. Even so I have never ever usedE#C(or seen it used); I can’t think of any reason to reuse an id across different pages.¹Admittedly in real life that selector won’t run in a loop, so the performance difference is not going to matter.