Higlight text from XPointer

22 views Asked by At

I'm looking for a way to highlight text segments from a kind XPointer, consisting of an XPath expression, an offset and a string length.

I've built a small module with XForms for indexing web page content for scholar purpose. This module allows me to save the XPointer of a selection, but now I'd like to be able to do the reverse, in order to visualize segments that have already been indexed.

Here's a small example of what I was able to achieve (but it doesn't work as expected):

  • Simple case, XPointer matches just text, works only once
  • Advenced case, XPointer matches mixed content, or content running over multiple paragraphs, doesn't work at all

NB: the solution needs to be only pure JS and if possible without external framework dependency...

As you can see, I'm not a JS guy... and any help would be appreciated! Thank you! Best, Josselin

<h1>Highlight</h1>
<h2>Simple case (works once...)</h2>
<button onclick="showEntry('//p[1]', 0, 3)">Push me to highlight</button>

<p>just plain text, no mixed content</p>

<h2>advanced case (doesn't work as expected)</h2>
<button onclick="showEntry('//p[2]', 2, 35)">Push me to highlight</button>
<p>With <i>mixed</i> content and text...</p>
<p>...running over more than one paragraph</p>
function showEntry(xpath, offset, length) {
   var element = document.evaluate(xpath, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
   if (element !== null) {
      console.log(element);
      element.scrollIntoView();
      
      var str = element.innerHTML;
      str = 
        str.substr(0, offset) +
        '<span class="showEntry">' + 
        str.substr(offset, length + 1) +
        '</span>' +
        str.substr(length + 1);
      element.innerHTML = str;
   }
};

See on Codepen

0

There are 0 answers