Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 26 additions & 22 deletions lib/dom.js
Original file line number Diff line number Diff line change
Expand Up @@ -257,23 +257,6 @@ var DocumentPosition = conventions.freeze({
});

//helper functions for compareDocumentPosition
/**
* Constructs a parent chain for a node.
*
* @param {Node} node
* The start node from which the parent chain will be constructed.
* @returns {Node[]}
* The array of nodes representing the parent chain from the root to the specified node.
*/
function parentChain(node) {
var chain = [];
while (node.parentNode || node.ownerElement) {
node = node.parentNode || node.ownerElement;
chain.unshift(node);
}
return chain;
}

/**
* Finds the common ancestor in two parent chains.
*
Expand Down Expand Up @@ -1476,15 +1459,36 @@ Node.prototype = {
: DocumentPosition.DOCUMENT_POSITION_PRECEDING)
);
}
var chain1 = parentChain(node1);
var chain2 = parentChain(node2);
if ((!attr1 && chain2.indexOf(node1) >= 0) || (attr2 && node1 === node2)) {
if (attr2 && node1 === node2) {
return DocumentPosition.DOCUMENT_POSITION_CONTAINS + DocumentPosition.DOCUMENT_POSITION_PRECEDING;
}
if ((!attr2 && chain1.indexOf(node2) >= 0) || (attr1 && node1 === node2)) {
if (attr1 && node1 === node2) {
return DocumentPosition.DOCUMENT_POSITION_CONTAINED_BY + DocumentPosition.DOCUMENT_POSITION_FOLLOWING;
}
var ca = commonAncestor(chain2, chain1);

var chain1 = [];
var ancestor1 = node1.parentNode;
while (ancestor1) {
if (!attr2 && ancestor1 === node2) {
return DocumentPosition.DOCUMENT_POSITION_CONTAINED_BY + DocumentPosition.DOCUMENT_POSITION_FOLLOWING;
}
chain1.push(ancestor1);
ancestor1 = ancestor1.parentNode;
}
chain1.reverse();

var chain2 = [];
var ancestor2 = node2.parentNode;
while (ancestor2) {
if (!attr1 && ancestor2 === node1) {
return DocumentPosition.DOCUMENT_POSITION_CONTAINS + DocumentPosition.DOCUMENT_POSITION_PRECEDING;
}
chain2.push(ancestor2);
ancestor2 = ancestor2.parentNode;
}
chain2.reverse();

var ca = commonAncestor(chain1, chain2);
for (var n in ca.childNodes) {
var child = ca.childNodes[n];
if (child === node2) return DocumentPosition.DOCUMENT_POSITION_FOLLOWING;
Expand Down
Loading