Error Documentation

Error Message

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

Where It Happened

document.getElementById('btn-format-json')
        .addEventListener('click', function () {
  // ...
});

What the situation?

  • A single index.js file is reused across multiple HTML pages.
  • On pages that do not contain the element with id="btn-format-json", the script still runs, tries to attach the event listener, and fails.
  • While On the page that does contain the button, there’s no error.

What Actually Happened?

  1. Browser loads the HTML file.
  2. Browser parses <script src="index.js"> and executes it immediately.
  3. document.getElementById('btn-format-json') runs:
    • If the element exists → returns a reference.
    • If the element doesn’t exist → returns null.
  4. When the code calls .addEventListener on null, JavaScript throws:
    Cannot read properties of null

Why this happen?

  • JavaScript is executed even if the element is not in the DOM of the current page.
  • Event listeners only work if the target element exists.

✅ Solutions

Since we already knew why it got error due to Javascript executed event listener event it does not exist in current html file. does it return error.

1. The solution is add checking before it call below code. how?

const btn = document.getElementById('btn-format-json');
if (btn) {
  btn.addEventListener('click', function () {
    // your handler
  });
}

2. By add checking to only allow execute only on Specific Page

if (window.location.pathname.includes("index.html")) {
  const btn = document.getElementById('btn-format-json');
  btn?.addEventListener('click', function () {
    // your handler
  });
}
        

By adding this check, it only executes if the current page is index.html. If your page is another HTML file, just replace index.html with that filename.

  
  if (window.location.pathname.includes("index.html")) {
 //code for index.html
}

Key Takeaways

  • A single JS file can safely be used across multiple HTML files.
  • Always check if an element exists before attaching event listeners.
  • The error happens because .addEventListener was called on null.