While working on a small project, I encountered a JavaScript error that reads:
script.js:5 Uncaught TypeError: Cannot set properties of null (setting 'onkeyup')
at script.js:5:18
Below is the HTML & JavaScript code snippet that triggered this error:
window.addEventListener("load", () => {
var filter = document.getElementById("the-filter"),
list = document.querySelectorAll("#the-list li");
filter.onkeyup = () => {
let search = filter.value.toLowerCase();
for (let i of list) {
let item = i.innerHTML.toLowerCase();
if (item.indexOf(search) == -1) { i.classList.add("hide"); }
else { i.classList.remove("hide"); }
}
};
});
#the-list {
list-style: none;
margin: 0;
padding: 0;
}
#the-list a {
text-decoration: none;
}
#the-list li {
padding: 10px;
border-bottom: 2px solid #ddd;
}
#the-list li:hover {
background: #ddd;
cursor: pointer;
}
#the-list li.hide {
display: none;
}
<input type="text" id="the-filter" placeholder="Search The Marketplace..."/>
<ul id="the-list">
<a href="a_link.htm"><li>Item</li></a>
<a href="a_link.htm"><li>Item1</li></a>
<a href="a_link.htm"><li>Item2</li></a>
<a href="a_link.htm"><li>Item3</li></a>
</ul>
Although I have identified the root cause of this issue, I am uncertain about the necessary fix. Despite displaying this error message, everything functions as expected when viewed in a web browser.