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.
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.
To compare values in a test, we can use the Node. js assert module.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With