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

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

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 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