Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

194
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!