我想使用XPath查找单词TEST并突出显示它。我已经设法使用var xpathResult = document.evaluate("(//text()[contains(., 'TEST')])[1]", document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null); var node=xpathResult.singleNodeValue;
搜索单词TEST我如何突出这个结果TEST在网页本身?谢谢你
突出显示返回的文本节点内容:
var xpathResult = document.evaluate("(//text()[contains(., 'TEST')])[1]", document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
var node = xpathResult.singleNodeValue;
if (node != null) {
var range = document.createRange();
range.selectNodeContents(node);
var span = document.createElement('span');
span.className = 'highlight';
range.surroundContents(span);
}
.highlight {
background-color: black;
color: white;
font-weight: strong;
font-size: 110%;
}
<p>This is a sentence.</p>
<p>This is a TEST.</p>
<p>The quick brown fox jumped over the lazy dog.</p>
突出显示子字符串:
var term = 'TEST';
var xpathResult = document.evaluate(`(//text()[contains(., '${term}')])[1]`, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
var node = xpathResult.singleNodeValue;
if (node != null) {
var range = document.createRange();
range.selectNodeContents(node);
var span = document.createElement('span');
span.className = 'highlight';
range.setStart(node, node.data.indexOf(term));
range.setEnd(node, node.data.indexOf(term) + term.length);
range.surroundContents(span);
}
.highlight {
background-color: black;
color: white;
font-weight: strong;
font-size: 110%;
}
<p>This is a sentence.</p>
<p>This is a TEST.</p>
<p>The quick brown fox jumped over the lazy dog.</p>