Reputation: 17077
Which one of the following selectors has better performance, if not the same
$('#location_form input#id_name')
$('#id_name')
I often have questions like the above pop up in my mind. I can't really answer them because I lack the knowledge on how selection work behind the scene.
My asks:
Thanks a bunch.
Upvotes: 4
Views: 370
Reputation: 4511
With your selectors, the latter is faster, as jQuery determines you only want to select by ID and returns document.getElementByID
: https://github.com/jquery/jquery/blob/master/src/core.js#L145-165
Here is the full source code: https://github.com/jquery/jquery/blob/master/src/core.js#L78-188
Upvotes: 3
Reputation: 30088
As usual, "it depends". For a trivially small document, there's not much difference.
For a larger document, #1 can have much better performance, because it limits the search to descendants of the element with the id of 'location_form', while #2 would search the entire document.
See http://api.jquery.com/category/selectors/ and more specifically, http://api.jquery.com/descendant-selector/
Upvotes: 3