How does jQuery traverse the DOM?

I was wondering how jQuery bypasses the DOM when using a selector. Does it look at each element of the "first level", and then looks at each of them? Or does he look at each child from these "first level" elements one by one?

Let me explain what I presented with some quick examples, given the following selector:

$("div p#target")

Does this continue:

 [1] <div> [3] <div> [5] <p id="target"></p> </div> </div> [2] <div> [4] <div> <p></p> </div> </div> 

Or how:

 [1] <div> [2] <div> [3] <p id="target"></p> </div> </div> <div> <div> <p></p> </div> </div> 
+6
source share
3 answers

The crawl happens in the same order as the elements in the DOM:

 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html> <head> <title>query traversal order</title> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script> </head> <body> <ul> <li id="parent1"> <ul> <li id="child1"></li> <li id="child2"></li> </ul> </li> <li id="parent2"> <ul> <li id="child3"></li> <li id="child4"></li> </ul> </li> </ul> <script type="text/javascript"> // keep a list of ids var arr = []; // loop over all li elements $('li').each(function(){ // add their id to the array arr.push($(this).attr('id')); }); // show contents of the array alert(arr.join(', ')); </script> </body> </html> 

This will warn "parent1, child1, child2, parent2, child3, child4";

+1
source

If you mean the order in which it goes through them, I assume that it is not jQuery itself, but the actual DOM functions. It probably depends on the implementation, and I will not rely on it (if perhaps it is not defined in the specifications).

What did you try to do to know such details? Perhaps we can help solve the real problem.

0
source

In your example, I hope that it will be processed as follows:

 <div> [2] <div> //check it matches the selector [1] <p id="target"></p> //document.getElementById is cheap </div> </div> <div> <div> <p></p> </div> </div> 
0
source

Source: https://habr.com/ru/post/900464/


All Articles