Troubleshooting a JavaScript error: Script.js throwing 'Uncaught TypeError' at line 5

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.

Answer №1

It appears that the input HTML document was not fully loaded

To address this issue, you can:

window.addEventListener('DOMContentLoaded', (event) => {
    // Add your code here
    // This will ensure it runs when the DOM is ready
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Angular 2 Element Selection: Dealing with Unrendered Elements

This form consists of three input fields: <div> <input *ngIf = "showInputs" #input1 (change)="onTfChnage(input2)" type="text"/> <input *ngIf = "showInputs" #input2 (change)="onTfChnage(input3)" type="text"/> <input *ngIf = "showInp ...

`asp:button displaying without any CSS applied`

asp:Button does not respond to CSS styling. CSS: .TabButton { border: none; background-size: cover; background-repeat: no-repeat; width: 100%; height: 100%; } HTML5: <asp:Button runat="server" Text="Events" CssClass ="TabButton" ...

Use JQuery to load a particular page by specifying its ID with the hashtag symbol

I am facing an issue where I need to create multiple private chatrooms per user. Although I have managed to make it work, I encountered a problem where if there are more than one private chats happening simultaneously, the content of these chats gets broad ...

Update the 'duplicate' buttons according to the position in the array

My app features 14 buttons, each generating a replica button with the same text when clicked. The pre-existing buttons are numbered to aid in iteration. I'm currently attempting to organize the newly created replica buttons in ascending order from lef ...

What causes TypeScript's ReadonlyArrays to become mutable once they are transpiled to JavaScript?

Currently, I am in the process of learning Typescript by referring to the resources provided in the official documentation. Specifically, while going through the Interfaces section, I came across the following statement: TypeScript includes a special t ...

Generate a JSON file using Node.js

I've been honing my skills with Node.js and express by working on a project involving a JavaScript object that generates a dropdown list. The process has been smooth so far. Recently, I integrated mongoose to create a model and saved it. Now, in my co ...

Refreshing express-session sessions

My goal is to enhance the user experience by retrieving their profile from the mongodb database when they visit the page, and then updating their session with this information. Currently, I am utilizing the following packages for managing sessions: - ex ...

How to keep jQuery horizontal submenu open when clicking on the menu

Seeking assistance with a menu issue. I have a horizontal menu with subitems that display when clicked, but having trouble with the submenu behavior. When clicking on a submenu item, I want it to remain open and show the related items underneath it. For ex ...

How can I add rows to the tbody of a table that is already inside a div container?

I have an existing table and I want to append a tbody element to it. Below is an example of the HTML table: <div id="myDiv"> <table class="myTable"> <thead> <tr> <th>ID</th> ...

Registration process in Node Express application encounters persistent loading when accessed through Postman

I've been working on a signup model for user accounts in Node.js, but when testing it in Postman, I encountered an issue where there was no response or failure. This left me stuck and I received the following error message in my terminal: Unhandled ...

The button's onclick function is failing to save the record in the database

Hello everyone, I am facing an issue with the ONCLICK button functionality. I have written code to save a form to the database. In the image, there are 2 buttons: Save button (type="submit") Save and New button (type="button") The Save button is ...

Transmitting PHP arrays to JavaScript through AJAX

I am struggling to retrieve an array from a SQL server using PHP and parse it to JavaScript using AJAX. Despite trying various solutions found through Google, I have been unable to successfully retrieve the array. Below is my PHP code: <?php inclu ...

Canvas displaying inaccurately (unsteady)

While working on a simple HTML5/javascript game, I encountered an unusual issue with the canvas drawings - they seem to be unstable. I have a map that needs to be drawn in a specific way: The background consists of 2 layers: the ocean and the islands. Th ...

What is the best method for automating the transfer of data from a database to the user interface of a website using html and javascript?

As a volunteer coordinator for a non-profit organization, I have some basic experience working with Python. I am willing to dedicate fewer than 8 hours of learning time to my current project in order to automate certain tasks (or else I will do them manual ...

What is the best way to iterate through a puppeteer selector's response in a loop?

So, by using page.evaluate I can accomplish the following: await page.evaluate(function() { var links = document.querySelectorAll('a'); for (var i = 0; i < links.length; i++) console.log(links[i].href); }); However, I am interested in a ...

Data is not being successfully passed through Ajax

Having some issues with passing data through ajax. I've used this method multiple times before without any problems, but now it's not returning anything. Here is the javascript code: $('#contactformbtn').click(function(){ var full ...

Tips for using the identical function on matched elements

I am working on a code where I want each textbox input to change its corresponding image. The function is the same for all partners in the list (txt & img). I have looked around and found some similar posts, but I am struggling to make the function wor ...

Having trouble with the auto width CSS for the center section of my webpage

I am facing an issue with assigning widths to my divisions using the CSS calc property. Despite setting the width for the first and last divisions, I am unable to allocate any width to the middle division. HTML: <div style="width:400px;"> <div ...

What steps should I take when dealing with two dynamic variables in a mediator script within the WSO2 ESB?

I'm facing an issue with my if condition - it doesn't work properly when the value is static. However, when I make `annee2` and `annee1` static (for example =2019), it works fine. Here's the code snippet: <script language="js"&g ...

Removing a dynamic component in Angular

Utilizing Angular dynamic components, I have successfully implemented a system to display toaster notifications through the creation of dynamic components. To achieve this, I have utilized the following: - ComponentFactoryResolve - EmbeddedViewRef - Ap ...