Some questions on how jquery selectors traverse a house

How to find out what happens with the DOM and what doesnโ€™t?

$('div p') 

This seems to return all div elements AND THEN performs another scan for P elements on each dom element that was returned in the first div search.

 $('div .foo') 

The class does not seem to scan dom. They only filter the previous $ ('div') list for elements containing the foo classes. If a child of $ ('div') has a class foo, it is not selected.

 $('div, div') 

It does not contain duplicates. So it looks like it only scans once with a list of lambdas that are either compared or not. But this is really confusing when you have filters like: contains ('x') that seem like they can overwrite dom themselves.

So how do these selectors work? Does "div.foo" only execute divs first and then filter for classes containing foo, or does it somehow turn into a calculation that says when tag == Div && class == Foo. How about when there are multiple selectors? They appear in the order in which they appeared on the page, without cheating, making me feel that he only scanned the house once. Maybe he just sorts and removes cheats before returning?

+7
source share
1 answer

jQuery optimizes the selector based on what's faster. If there is a native browser-supported method for receiving an element (getElementById, etc.), it will use it, otherwise it will be filtered based on the results of principle-based methods.

+2
source

All Articles