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

178
Vistas
Highlight word in webpage without .innerhtml

I want to highlight a word in a page without involving the document.body.innerHTML as this totally alters the functionality of the page.

Is there any other way to do it?

Right now I am using this code to highlight

document.body.innerHTML= document.body.innerHTML.replace(/TEST/g, function(m){
    return '<span style="background-color:YELLOW">'+m+'</span>'
}

Thank you

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

If I understand your problem correctly, I would suggest to retrieve the DOM elements with the relevant content, get the content, and finally surround it with a styled span element.

const $matchedElements = document.querySelectorAll("p");

$matchedElements.forEach(($element) => {
  if ($element.innerHTML.match("SampleCollected")) {
    const $mySpan = document.createElement("span");
    $mySpan.style = "background-color:yellow";
    $mySpan.innerHTML = $element.innerHTML;

    $element.innerHTML = ""
    $element.appendChild($mySpan)
  }
});
<!DOCTYPE html>
<html>
  <head>
    <title>Example</title>
    <meta charset="UTF-8" />
  </head>

  <body>
    <p>
      SampleCollected
    </p>
    <p>
      SampleNotCollected
    </p>
    <p>
      SampleCollected
    </p>

    <script src="src/index.js"></script>
  </body>
</html>

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