Highlight when sending HTML and Xpath

Given HTML as a string, Xpath, and offsets. I need to highlight this word.

In the following case, I need to highlight Child 1

HTML text:

<html>
 <body>
       <h2>Children</h2>Joe has three kids:<br/>
       <ul>
        <li>
        <a href="#">Child 1 name</a>
        </li>
        <li>kid2</li>
        <li>kid3</li>
       </ul>
 </body>
</html>

XPATH as: /html/body/ul/li[1]/a[1]

Offsets: 0,7

Render - I use reactin my application. The following shows what I have done so far.

public render(){
  let htmlText = //The string above
  let doc = new DOMParser().parseFromString(htmlRender,'text/html');
  let ele = doc.evaluate("/html/body/ul/li[1]/a[1]", doc, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null); //This gives the node itself
  let spanNode = document.createElement("span");
  spanNode.className = "highlight";

  spanNode.appendChild(ele);
  // Wrapping the above node in a span class will add the highlights to that div
  //At this point I don't know how to append this span to the HTML String
  return(
    <h5> Display html data </h5>
    <div dangerouslySetInnerHTML={{__html: htmlText}} />
   )

I want to avoid using jquery. Want to do it in Javascript (if there is a risk)!

Edit:

So, if you notice a function Render, it uses dangerouslySetHTML. My problem is that I cannot manipulate the line that is displayed.

+6
source share
2 answers

Here is what I did.

public render(){
  let htmlText = //The string above
  let doc = new DOMParser().parseFromString(htmlRender,'text/html');
  let xpathNode = doc.evaluate("/html/body/ul/li[1]/a[1]", doc, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null); 
  const highlightedNode = xpathNode.singleNodeValue.innerText;
  const textValuePrev = highlightedNode.slice(0, char_start);
  const textValueAfter = highlightedNode.slice(char_end, highlightedNode.length);
  xpathNode.singleNodeValue.innerHTML = `${textValuePrev}
                                         <span class='pt-tag'>
                                         ${highlightedNode.slice(char_start, char_end)}
                                         </span> ${textValueAfter}`;
  return(
    <h5> Display html data </h5>
    <div dangerouslySetInnerHTML={{__html: doc.body.outerHTML}} />
   )
+5
source

Xpath -, React . Xpath , DOM . , DOM Xpath.

https://jsfiddle.net/69z2wepo/73860/

var HighlightXpath = React.createClass({
  componentDidMount() {
     let el = document.evaluate(this.props.xpath, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
     el.singleNodeValue.style.background = 'pink';
  },
  render: function() {
    return this.props.children;
  }
});

:

<HighlightXpath xpath="html//body//div/p/span">
    ... app ...
</HighlightXpath>
+3

Source: https://habr.com/ru/post/1015851/


All Articles