Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

124
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda