In IE, we can use sourceIndex. In standard browsers, we can use compareDocumentPosition. But what about the old standard browsers? What about XML? Therefore, we need to determine the relationship between a node and another node based on its attributes.
My idea is simple. If they are the same, 0 is returned (for deduplication). If their parent nodes are the same, the order of the two is determined based on nextSibling, otherwise, we will find the two parent nodes closest to the recent common ancestor and the other two (the father and the uncle in the point of human nature ), isn't it the same as the parent node ?! According to nextSibling, their order is the order of their children (so a father named Li Gang is very important in this world !) However, sometimes the recent public ancestor is one of the two sides. Of course it is the latest.
The remaining problem is the issue of finding the recent common ancestor. My thinking is also very simple, not necessarily efficient. After all, the University has ruined all mathematics. Keep getting up their parent nodes until the top HTML elements, together with the original node, constitute two arrays. Then, compare the final elements of the array. If they are the same, remove them, because the same elements are common ancestor. If they are different, retrieve one of them.
The following is the test page and source code:
Because window. console is used, we recommend that you view the results in firefox, IE8, and chrome.
<! Doctype html> <pead> <title> node sorting </title> </pead> <body> </ptml>
[Ctrl + A select all Note: If you need to introduce external Js, You need to refresh it to execute]