> From: Brendan O'Brien > > I have a somewhat related observation. I have discovered > that when selecting by ID, the context parameter does not > matter. In other words, these two statements are > functionally equivalent: > > $("#myId"); > and > $("#myId", myContext); > > It's as if when the id selector is passed then the $ method > just uses a document.getElementById.
Indeed it does just that. See this code in jquery.js: var re2 = /^([#.]?)([a-z0-9\\*_-]*)/i; var m = re2.exec(t); if ( m[1] == "#" ) { // Ummm, should make this work in all XML docs var oid = document.getElementById(m[2]); r = ret = oid ? [oid] : []; t = t.replace( re2, "" ); } else { if ( !m[2] || m[1] == "." ) m[2] = "*"; for ( var i = 0; i < ret.length; i++ ) r = jQuery.merge( r, m[2] == "*" ? jQuery.getAll(ret[i]) : ret[i].getElementsByTagName(m[2]) ); } > Besides the fact that this may produce unexpected results... Well, IDs are supposed to be unique in a document, so $("myId",myContext) doesn't seem all that useful even if the code did make use of it. It would reject the case where #myId exists but is outside of myContext, and work the same as the current code in the the other two cases (myId doesn't exist, or myId does exist inside myContext). Is that what you were trying to do - operate on element #myId but only if that element is inside myContext, ignoring it if that element is outside myContext? If that's not the requirement, then you can just leave out myContext. > it also means that you should be careful when using IDs > to try to gain performance. Because if the size of your > markup is large then this > > $("#myId", myContext); > > may actually be slower then this > > $(".myClass", myContext); > > I have definitely seen performance gains by using the second > one over the first. That's an interesting result. I would have guessed (hoped?) that #myId should be fast even in a large document - don't most browsers load all the IDs into a hash table? I wonder how the comparison turns out in different browsers. You might try the comparison with $("myId") instead of $("#myId",myContext), but I'll bet it wouldn't make any difference since the code doesn't use the context. (This should certainly be documented if it isn't already.) -Mike _______________________________________________ jQuery mailing list discuss@jquery.com http://jquery.com/discuss/