In IE we can use sourceIndex, and in standard browsers we can use compareDocumentPosition, but what about older 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 very simple. If they are the same, return 0 (for deduplication). If their parent nodes are the same, then determine the order of the two based on nextSibling. Otherwise, find their nearest common ancestor and the other two Aren't the two parent nodes closest to this ancestor (from a human point of view, uncle and father) the same situation as the parent node? ! Their order is determined based on nextSibling, and their order is the order of their children (so it is very important to have a father named Li Gang, in this hereditary world!) However, sometimes the most recent common ancestor is one of the two parties, That's certainly as recent as it gets.
The remaining problem is to find the most recent common ancestor. My idea is also very simple, not necessarily efficient. After all, mathematics has been abandoned in universities. Continue to get their parent nodes upward until the top HTML element, together with the original node, forms two arrays. Then take the last elements of the array each time for comparison. If they are the same, remove them, because the same ones are common ancestors. If they are not the same, just take one of them.
The following is the test page and source code:
Since window.console is used, it is recommended to view the results under firefox, IE8, and chrome.