Search code examples
javascriptregexsearchreplacehighlight

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

Solution

  • 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>`);
    }