How can I learn how jQuery selectors work behind t

2020-02-09 07:35发布

For example, when we use $('div span'), how does jQuery do such a search for us?

Does it search for the span element first or the div?

It seems that the jQuery official site has no explanation on these things; it just show us what's functions are available through the API.

I want to know how every type jQuery selector is implemented, so I can select the best selector to use.

Do you know where I can get such info?

5条回答
兄弟一词,经得起流年.
2楼-- · 2020-02-09 08:03

As @Juhana has commented, if you want to know the specific methods jQuery uses to select objects based on its selectors, look at the github repository:

https://github.com/jquery/jquery/

Alternatively, look at the source code available in the uncompressed jQuery download:

http://jquery.com/download/

If you just want to know what different selectors are available for you, jQuery provides a list of them here:

http://api.jquery.com/category/selectors/

查看更多
在下西门庆
4楼-- · 2020-02-09 08:10

The simplest place to look for would be reading straight from the source. Download the uncompresserd source from jquery site and read from the raw source what it does and in which order.

http://jquery.com/download/

查看更多
老娘就宠你
5楼-- · 2020-02-09 08:11

It searches for the span elements first. It parses the selector as:

  1. Any element with tagName = span
  2. Having an ancestor with tagName = div

For the first part it can use the getElementsByTagName method to find all span elements, then it has to loop through the ancestors of each to look for div elements.

查看更多
手持菜刀,她持情操
6楼-- · 2020-02-09 08:16

Broadly, what you need to know:

  1. jQuery reads selectors from right to left.
  2. Using an exact ID is fastest, followed by using an exact tag name, because they use optimized JavaScript-native methods.
  3. Native CSS selectors like :first-child are faster than jQuery selectors like :first.

You can also read the official Sizzle documentation, but it doesn't really discuss optimization techniques.

查看更多
登录 后发表回答