Skip to content

Commit

Permalink
Fix issue with preceding:: axis in document fragments
Browse files Browse the repository at this point in the history
  • Loading branch information
JLRishe committed Jan 7, 2016
1 parent fbd9f1b commit 9b75e8a
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 3 deletions.
20 changes: 20 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -675,7 +675,27 @@ module.exports = {
assert.ok(xpath.select1('/book/characters', doc));

assert.equal(xpath.select1('local-name(/book/characters)', doc), 'characters');

test.done();
}

,"preceding:: axis works on document fragments": function (test) {
var doc = new dom().parseFromString('<n />'),
df = doc.createDocumentFragment(),
root = doc.createElement('book');

df.appendChild(root);

for (var i = 0; i < 10; i += 1) {
root.appendChild(doc.createElement('chapter'));
}

var chapter = xpath.select1("book/chapter[5]", df);

assert.ok(chapter, 'chapter');

assert.equal(xpath.select("count(preceding::chapter)", chapter), 4);

test.done();
}
}
17 changes: 14 additions & 3 deletions xpath.js
Original file line number Diff line number Diff line change
Expand Up @@ -1663,6 +1663,18 @@ PathExpr.prototype.init = function(filter, filterPreds, locpath) {
this.locationPath = locpath;
};

/**
* Returns the topmost node of the tree containing node
*/
function findRoot(node) {
while (node && node.parentNode) {
node = node.parentNode;
}

return node;
}


PathExpr.prototype.evaluate = function(c) {
var nodes;
var xpc = new XPathContext();
Expand Down Expand Up @@ -1910,9 +1922,8 @@ PathExpr.prototype.evaluate = function(c) {
if (xpc.virtualRoot != null) {
st = [ xpc.virtualRoot ];
} else {
st = xpc.contextNode.nodeType == 9 /*Node.DOCUMENT_NODE*/
? [ xpc.contextNode ]
: [ xpc.contextNode.ownerDocument ];
// cannot rely on .ownerDocument because the node may be in a document fragment
st = [findRoot(xpc.contextNode)];
}
outer: while (st.length > 0) {
for (var m = st.pop(); m != null; ) {
Expand Down

0 comments on commit 9b75e8a

Please sign in to comment.