简体   繁体   中英

How does caching selectors work under the hood

This is a pretty generaly question.
Is:

$el.siblings(".class"); 

better practice than

$("#id") 

to access an element when $el has already been used before and is therefore already stored in a variable?

I am a bit unsure about this for a few reasons:

  • id is apparently very fast;
  • I am not entirely sure if the DOM needs to be traversed to get the sibling element when the original element got cached.

Following this question, I wonder how jQuery keeps reference to an internal DOM node when caching the selector (eg. $el = $("#el"); ). Although I know the syntax, I'm not sure about what happens under the hood (ie. how keeping the reference is programmed in JS).

Any formal confirmation on this?

Under the hood, jQuery just has a reference to the DOM element. Every time you do:

$("#el")

jQuery has to parse the selector to determine that it's looking for an ID, then call document.getElementById("el") . It saves the result of this in the jQuery object. If you do:

$el = $("#el");

and then use $el from then on, it doesn't have to do any parsing, and it doesn't have to call getElementById() to find the element. All the jQuery methods can simply use the instance variable that contains the saved DOM element.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM