简体   繁体   中英

Convert XPath to Node

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 '';
  }
}

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)


Edit related to the comment

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM