Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I test which node comes first?

I have two given nodes that are stored inside variables. Is there a simple, low resource usage, solution to find which node comes first in the document? Both nodes should be siblings but may be many nodes apart.

like image 494
www139 Avatar asked Dec 21 '15 23:12

www139


People also ask

What is the name of the method to check equality of two nodes?

The isEqualNode() method of the Node interface tests whether two nodes are equal. Two nodes are equal when they have the same type, defining characteristics (for elements, this would be their ID, number of children, and so forth), its attributes match, and so on.

Which core module in node can you use for testing?

To compare values in a test, we can use the Node. js assert module.


1 Answers

Try compareDocumentPosition:

function theFirst(node1, node2) {
  return node1.compareDocumentPosition(node2)
    & Node.DOCUMENT_POSITION_FOLLOWING ? node1 : node2;
}

Note that if the nodes are in different trees, the result may be random (but consistent). You can filter out that case with & Node.DOCUMENT_POSITION_DISCONNECTED and return e.g. undefined.

like image 165
Oriol Avatar answered Sep 18 '22 10:09

Oriol