Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

113
Views
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

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!