TypeError: Cannot read properties of null (reading 'addEventListener') [Solved]

TypeError: Cannot read properties of null (reading 'addEventListener') [Solved]

This article talks about an error that can happen when using JavaScript in your web projects. It's about an error message that might show up, saying something like "'TypeError: Cannot read properties of null (reading 'addEventListener')'". If you're curious about this error or facing it in your project, by the end of this article, you'll know how to fix it and stop it from happening again in the future.

JavaScript is a useful tool for making web applications, along with HTML and CSS. But sometimes, especially if you're new to JavaScript language, you might run into errors. These errors can make your project not work like you want it to, or even crash it. Some errors are easy to solve, but others can be really frustrating. This article talks about the JS error mentioned earlier, as well as another one you can read about the TypeError: cannot set properties of undefined.

What is 'TypeError: Cannot read properties of null (reading 'addEventListener')' error in JS means?

The 'TypeError: Cannot read properties of null (reading 'addEventListener')' arises when we attempt to add an addEventListener to a variable or null DOM object. In JS, the addEventListener property can be only added to a defined element or DOM object. Fail to define or intialize the DOM Object before the script loaded, the said JS Type Error will be thrown.

Possible Cause #1:

One of the potential reasons for encountering a 'TypeError: Cannot read properties of null (reading 'addEventListener')' error is when there's an inadvertent mismatch in identifying the class name or ID of the specific element.

Here's a sample JS snippet that illustrate the said scenario:

HTML Code:

  1. <!DOCTYPE html>
  2. <html lang="en">
  3.     <meta charset="UTF-8">
  4.     <meta name="viewport" content="width=device-width, initial-scale=1.0">
  5.     <title>Sample Site</title>
  6.     <style>
  7.         #sampleEl{
  8.             width: 300px;
  9.             height: 300px;
  10.             border: 1px solid gray;
  11.             border-radius: 15px;
  12.             display: flex;
  13.             align-items: center;
  14.             justify-content: center;
  15.             color: rgb(192, 192, 192);
  16.         }
  17.     </style>
  18. </head>
  19.     <div id="sampleEl">
  20.         <small><i>Click Here!</i></small>
  21.     </div>
  22.     <script src="./script.js"></script>
  23. </body>
  24. </html>

JS Code:

  1. // Sample Undefined/Null Element/ DOM Object
  2. const SampleEl = document.getElementById('SampleEl')
  3.  
  4. // Adding a click event script to null object
  5. SampleEl.addEventListener('click', function(e){
  6.     e.preventDefault()
  7.     alert('Sample Element')
  8. })

Even if the element ID is spelled correctly, executing the provided code snippet will lead to an error appearing in your browser's DevTools console log. This error is illustrated in the following image and is attributed to issues with case sensitivity.

TypeError: Cannot read properties of null (reading 'addEventListener')

Solution 1.1:

One way to prevent the occurrence of the error outlined in the initial error cause is to incorporate a conditional parameter into your JavaScript code utilizing the If Statement. By employing this If statement, you can initially verify or validate whether the chosen DOM object or element exists or has already been loaded. To gain a clearer understanding, refer to the subsequent snippet.

  1. // Sample Undefined/Null Element/ DOM Object
  2. const SampleEl = document.getElementById('SampleEl')
  3.  
  4. // Check if DOM Element Exists
  5. if(SampleEl != null){
  6.     // Adding a click event script to null object
  7.     SampleEl.addEventListener('click', function(e){
  8.         e.preventDefault()
  9.         alert('Sample Element')
  10.     })
  11. }else{
  12.     console.warn(`#SampleEl Object or Element Does not exists or not yet loaded.`)
  13. }

TypeError: Cannot read properties of null (reading 'addEventListener')

Solution 1.2:

Moreover, JavaScript also provides a valuable tool known as the optional chaining operator (?.). This operator serves to inspect the element or object initially, and in the event it is null, the subsequent script will be bypassed, effectively preventing the occurrence of an error.

Here's the following sample snippet that illustrate this solution:

  1. // Sample Undefined/Null Element/ DOM Object
  2. const SampleEl = document.getElementById('SampleEl')
  3.  
  4. // Using Optional Chaning operator
  5. // Adding a click event script to null object
  6. SampleEl?.addEventListener('click', function(e){
  7.     e.preventDefault()
  8.     alert('Sample Element')
  9. })

Possible Cause #2:

Another factor that can trigger the 'TypeError: Cannot read properties of null (reading 'addEventListener')' error message in JavaScript is when the JS script is loaded or executed prior to the element being fully loaded. Successfully selecting an element or DOM object in JavaScript relies on the condition that the specific element is already loaded.

Here's an example for this scenario:

  1. <!DOCTYPE html>
  2. <html lang="en">
  3.     <meta charset="UTF-8">
  4.     <meta name="viewport" content="width=device-width, initial-scale=1.0">
  5.     <title>Sample Site</title>
  6.     <style>
  7.         #sampleEl{
  8.             width: 300px;
  9.             height: 300px;
  10.             border: 1px solid gray;
  11.             border-radius: 15px;
  12.             display: flex;
  13.             align-items: center;
  14.             justify-content: center;
  15.             color: rgb(192, 192, 192);
  16.         }
  17.     </style>
  18.     <script>
  19.         // Sample Element/ DOM Object
  20.         const SampleEl = document.getElementById('sampleEl')
  21.  
  22.         // Adding a click event script
  23.         SampleEl.addEventListener('click', function(e){
  24.             e.preventDefault()
  25.             alert('Sample Element')
  26.         })
  27.     </script>
  28. </head>
  29.     <div id="sampleEl">
  30.         <small><i>Click Here!</i></small>
  31.     </div>
  32. </body>
  33. </html>

Despite correctly selecting the element or DOM object using the appropriate selector, the variable will retain a null value because the script is loaded prior to the element itself.

Solution 2.1:

To resolve the error in the given snippet, the solution is to relocate the script to the end or immediately after the element is defined. This guarantees that the element will be loaded prior to appending the addEventListener property or event to the selected DOM object.

  1. <!DOCTYPE html>
  2. <html lang="en">
  3.     <meta charset="UTF-8">
  4.     <meta name="viewport" content="width=device-width, initial-scale=1.0">
  5.     <title>Sample Site</title>
  6.     <style>
  7.         #sampleEl{
  8.             width: 300px;
  9.             height: 300px;
  10.             border: 1px solid gray;
  11.             border-radius: 15px;
  12.             display: flex;
  13.             align-items: center;
  14.             justify-content: center;
  15.             color: rgb(192, 192, 192);
  16.         }
  17.     </style>
  18. </head>
  19.     <div id="sampleEl">
  20.         <small><i>Click Here!</i></small>
  21.     </div>
  22.     <script>
  23.         // Sample Element/ DOM Object
  24.         const SampleEl = document.getElementById('sampleEl')
  25.  
  26.         // Adding a click event script
  27.         SampleEl.addEventListener('click', function(e){
  28.             e.preventDefault()
  29.             alert('Sample Element')
  30.         })
  31.     </script>
  32. </body>
  33. </html>

Solution 2.2:

Furthermore, the provided snippet can be rectified by utilizing the onload event listener attached to the document. This ensures that the entire web document is fully loaded before executing subsequent scripts.

Below is an example snippet demonstrating this solution:

  1. <!DOCTYPE html>
  2. <html lang="en">
  3.     <meta charset="UTF-8">
  4.     <meta name="viewport" content="width=device-width, initial-scale=1.0">
  5.     <title>Sample Site</title>
  6.     <style>
  7.         #sampleEl{
  8.             width: 300px;
  9.             height: 300px;
  10.             border: 1px solid gray;
  11.             border-radius: 15px;
  12.             display: flex;
  13.             align-items: center;
  14.             justify-content: center;
  15.             color: rgb(192, 192, 192);
  16.         }
  17.     </style>
  18.     <script>
  19.         window.onload = function(){
  20.             // Sample Element/ DOM Object
  21.             const SampleEl = document.getElementById('sampleEl')
  22.  
  23.             // Adding a click event script
  24.             SampleEl.addEventListener('click', function(e){
  25.                 e.preventDefault()
  26.                 alert('Sample Element')
  27.             })
  28.         }
  29.     </script>
  30. </head>
  31.     <div id="sampleEl">
  32.         <small><i>Click Here!</i></small>
  33.     </div>
  34. </body>
  35. </html>

Conclusion:

Simplifying things, the 'TypeError: Cannot read properties of null (reading 'addEventListener')' error emerges when we attempt to select an element or DOM object that doesn't yet exist or hasn't been loaded. This error arises due to the potential causes outlined above. The solutions provided earlier can prevent this error from occurring.

And there you have it! I trust that this guide addressing the origins and remedies for the JS TypeError: Cannot read properties of null (reading 'addEventListener') message has provided you with the insights you sought.

For more Free Source Codes, Tutorials, and Articles to enhance your programming skills, don't hesitate to explore further on this website.

You might want to download the following JS projects:

Add new comment