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

192
Vistas
How can I highlight search results live with JavaScript?

I am trying to find a way to highlight search results live as the user enters a search term into the input field. The target of the search is an unordered list. I am trying to use regex to highlight matches, but when I try to replace the results with a highlighted version of themselves I get an Undefined TypeError:

"Cannot read properties of undefined (reading 'replace')"

I know that the error is in the last line of the displayMatches function but I can't figure out the correct syntax. Would anyone be able to help?

Here's the HTML:

         <ul>
            <li>item 1</li>
            <li>item 2</li>
            <li>item 3</li>
            <li>item 4</li>
            <li>item 5</li>
            <li>item 6</li>
            <li>item 7</li>
            <li>item 8</li>
            <li>item 9</li>
           <li>item 10</li>
        </ul>
      
     
        <input id="search" type="text">

JavaScript:

let searchBar = document.getElementById("search");

const displayMatches = () => {
let userInput = document.getElementById("search").value;
let target = document.getElementsByTagName("li");
let regex = new RegExp(`${userInput}`, 'g');
target.innerHTML = target.innerText.replace(regex, match => `<mark>${match}</mark>`);
}

searchBar.addEventListener('keyup', displayMatches);
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

The error is target.innerHTML and target.innerText

You got target from document.getElementsByTagName("li"). This statement returns an array of all of your li elements. But the innerHTML and the innerText propertys can't handle arrays, they just can handle single elements, so you have to loop through your lis:

for (i = 0; i < target.length; i++) {
    target[i].innerHTML = target[i].innerText.replace(regex, match => `<mark>${match}</mark>`);
}
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