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'm trying top use regex to highlight matches but when I try to replcase 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? Thank you.
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);
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 li
s:
for (i = 0; i < target.length; i++) {
target[i].innerHTML = target[i].innerText.replace(regex, match => `<mark>${match}</mark>`);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.