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

303
Vistas
Problem developing a text searcher javascript

I wanted to highlight/style specific words of a text using js.

index.html

<body>

    <p id="lorem">
        Lorem ipsum dolor sit amet consectetur adipisicing elit. 
        Magni iure doloremque maiores cupiditate quae! 
        Sed dolorum quibusdam ex Lorem vero optio assumenda tenetur iure dolor molestiae, 
        eius eum sequi dolore repellat.
    </p>
    <button onclick="check()">
        check
    </button>

    <script src="./script.js">
    </script>

</body>

script.js

function check(){
  let ipsum = document.getElementById("lorem")
  let vipsum = ipsum.innerHTML

  let elit = vipsum.search(/elit/ig )

  if(elit){
    console.log("so, we have a match")    
    vipsum.substring(elit, 4)

    let highlight = document.querySelector("#lorem").innerHTML[19];
    highlight.style.color: "red"  //Error can't style undefined

  }else{
    console.log("no word matching")
  }

}

I can get the matched string in the console but can't style it in the DOM, I wanted to ask if it was possible to do something like this in javascript.

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

0

In general you can't apply styling to a string you have to apply styling to an html element. When you execute document.querySelector("#lorem").innerHTML it returns a string.

One possible solution is to wrap your matched text in an element which can be styled:

function check(){
  let ipsum = document.getElementById("lorem")
  let vipsum = ipsum.innerText

  let matches = vipsum.split(/(elit)/ig)

  if(matches.length > 1){
    console.log("so, we have a match")
    ipsum.innerHTML = matches.map((str, i) => 
       (i % 2) === 1 ? `<span class=highlight>${str}</span>` : str
    ).join('')
  }else{
    console.log("no word matching")
  }
}
.highlight {color: red;}
<p id="lorem">
Lorem ipsum dolor sit amet consectetur adipisicing elit. 
Magni iure doloremque maiores cupiditate quae! 
Sed dolorum quibusdam ex Lorem vero optio assumenda tenetur iure dolor molestiae, 
eius eum sequi dolore repellat.
</p>

<button onclick="check()">check</button>

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