Jed Grant
Jed Grant

Reputation: 1425

How do I get a relative Xpath using Javascript

Update: This question was part of a larger effort to try and highlight text and store that highlight in a database so it could be loaded later.

I'm following the code used here: Range object with JSON I am trying to capture the position of text selected by the user to store in a database and then restore on an ajax call.

First, I want to make the xpath I am getting that looks like this

endXPath: "/HTML[1]/BODY[1]/DIV[1]/DIV[5]/P[3]/text()[1]"

To look like this

endXPath: "/DIV[5]/P[3]/text()[1]"

Where DIV[1] in the first example has an ID of "content."

I believe this path is coming from this function

function makeXPath (node, currentPath) {
  /* this should suffice in HTML documents for selectable nodes, XML with namespaces needs     more code */
  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 '';
  }
}

From what I've read so far I am guessing I need to change the contextNode? But I'm not sure how to accomplish that either.

Upvotes: 1

Views: 1217

Answers (1)

Jed Grant
Jed Grant

Reputation: 1425

There's a JQuery plugin that accomplishes this call Annotator. It has everything already built in to highlight, store the highlight and add a comment regarding the highlight.

Upvotes: 1

Related Questions