Reputation: 8531
I am wondering how to convert an XPath to a Node object?
The reason why I ask is because I am trying to create a Range object, and set the range with the XPath. Below is the code I have written, but from my understanding it will not work becasue setRange() and setEnd() needs a Node object as its first parameter.
var range = document.createRange();
range.setStart(startXPath, startOffset);
range.setEnd(endXPath, endOffset);
EDIT: This is how I'm getting my XPath:
function grabSelection() {
var selection = window.getSelection();
var range = selection.getRangeAt(0);
var selectObj = {
'startXPath': makeXPath(range.startContainer),
'startOffset': range.startOffset,
'endXPath': makeXPath(range.endContainer),
'endOffset': range.endOffset
}
return selectObj
}
function makeXPath (node, currentPath) {
currentPath = currentPath || '';
switch (node.nodeType) {
case 3:
case 4:
return makeXPath(node.parentNode, 'text()[' + (document.evaluate('preceding-sibling::text()', node, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null).snapshotLength + 1) + ']');
case 1:
return makeXPath(node.parentNode, node.nodeName + '[' + (document.evaluate('preceding-sibling::' + node.nodeName, node, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null).snapshotLength + 1) + ']' + (currentPath ? '/' + currentPath : ''));
case 9:
return '/' + currentPath;
default:
return '';
}
}
Upvotes: 2
Views: 1672
Reputation: 117354
Assuming the thing you called "XPath" is the result of a XPath-query, this returns a DOMNodelist, so you must set
startXPath to XPathResult[0]
and
endXPath to XPathResult[XPathResult.length-1]
(where XPathResult is the nodelist returned by XPath->query)
As startXPath and endXPath are really XPath'es, you need to evaluate them to get the nodes:
var startXPath = document.evaluate(startXPath, document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null).snapshotItem(0);
var endXPath = document.evaluate(endXPath, document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null).snapshotItem(0);
Can you explain what you try to achieve, maybe there is an better approach?
Upvotes: 1