How does jQuery selection behind the scenes work?

Which of the following selectors has the best performance, if not the same

  • $('#location_form input#id_name')
  • $('#id_name')

I often have questions like the ones above. I can not answer them because I lack knowledge on how to select work behind the scenes.

My question is:

  • answer / opinions to the question above
  • links explaining how jQuery selections work behind the scenes
  • do all javascript frameworks work the same as jQuery when it comes to choices?

Thanks a lot.

+4
source share
2 answers

With your selectors, the latter is faster because jQuery determines that 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 complete source code: https://github.com/jquery/jquery/blob/master/src/core.js#L78-188

+3
source

As usual, "it depends." For a trivially small document, there is not much difference.

For a larger document, # 1 can have much better performance because it restricts the descendants to searching for an element with the identifier 'location_form', and # 2 will search the entire document.

See http://api.jquery.com/category/selectors/ and more specifically http://api.jquery.com/descendant-selector/

+3
source

All Articles