Reputation: 3205
I found this piece of code in a jQuery plugin:
$("#"+id,$t.grid.bDiv).css("display","none");
The second parameter to $()
changes the context of the search, right? Does it still make sense to include it, since the line is already searching for the ID? Doesn't jQuery search the whole document when specifying ID?
UPDATE:
@casablanca - are you sure it just calls the native getElementById() ? Because i changed that line to document.getElementById('id').style.display = "none"
and the performance became significantly faster (since that line is inside a loop). I tested using IE8 by the way.
Upvotes: 0
Views: 56
Reputation: 27411
It seems necessary. But I did a quick test here anyway. The finding is, jQuery (unsurprisingly) doesn't care your #id is unique or not. In the code:
alert($("#test", ".test2").html());
This returns within test2, which is correct, and if we put:
alert($("#test").html());
i.e. without context, it returns within test1
What I am guessing the reason behind the plugin writer you mentioned, is to prevent someone who used the plugin and accidently use the same ID as the one he is using there. This ensures no matter what you type in HTML, his plugin would works.
Thanks for this finding. I think I would include this in authoring plugins.
Upvotes: 2
Reputation: 70701
No, it doesn't help at all. If you specify the ID, the element is retrieved directly via the native document.getElementById
method, which doesn't require any context and is very fast anyway.
Upvotes: 1