突出显示给出HTML和Xpath的时间 [英] Highlighting when HTML and Xpath is given
问题描述
给出HTML作为字符串,Xpath和偏移量.我需要强调这个词.
Given the HTML as a string, the Xpath and offsets. I need to highlight the word.
在以下情况下,我需要突出显示 Child 1
In the below case I need to highlight Child 1
HTML文本:
<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为:/html/body/ul/li [1]/a [1]
偏移量: 0,7
渲染-我在我的应用中使用 react
.以下是我到目前为止所做的.
Render - I am using react
in my app.
The below is 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}} />
)
我想避免使用jquery.如果可能的话,想用Javascript做(也可以做!)!
I want to avoid using jquery. Want to do in Javascript(React too) if possible!
因此,如果您注意到 Render
函数,它正在使用 dangerouslySetHTML
.我的问题是我无法操纵呈现的字符串.
So if you notice the Render
function it is using dangerouslySetHTML
.
My problem is I am not able manipulate that string which is rendered.
推荐答案
这就是我最终要做的事情.
This is what I ended up doing.
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}} />
)
这篇关于突出显示给出HTML和Xpath的时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!