Vicky Lahkar
Vicky Lahkar

Reputation: 25

Highlight a word in webpage using XPath

I want to look for a word TEST using XPath and highlight it. I have managed to search for the word TEST using var xpathResult = document.evaluate("(//text()[contains(., 'TEST')])[1]", document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null); var node=xpathResult.singleNodeValue;

How do I highlight this result TEST in webpage itself? Thank you

Upvotes: 0

Views: 289

Answers (1)

Martin Honnen
Martin Honnen

Reputation: 167691

Highlighting the returned text node contents:

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>

Highlighting the substring:

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>

Upvotes: 1

Related Questions