Uncaught TypeError: Cannot read properties of null (reading 'addEventListener')
document.getElementById('btn-format-json')
.addEventListener('click', function () {
// ...
});
index.js
file is reused across multiple HTML pages.id="btn-format-json"
, the
script still runs, tries to attach the event listener, and fails.
<script src="index.js">
and executes it immediately.document.getElementById('btn-format-json')
runs:
null
..addEventListener
on null
, JavaScript throws:
Cannot read properties of null
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.
const btn = document.getElementById('btn-format-json');
if (btn) {
btn.addEventListener('click', function () {
// your handler
});
}
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
}
.addEventListener
was called on null
.