Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

114
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda