Sometimes, we may run into the JavaScript ‘document.querySelector(…) is null’ error when we try to select an element that’s loading in our JavaScript app.
In this article, we’ll look at how to fix the JavaScript ‘document.querySelector(…) is null’ error when we try to select an element that’s loading in our JavaScript app.
Fix the JavaScript ‘document.querySelector(…) is null’ Error
To fix the JavaScript ‘document.querySelector(…) is null’ error when we try to select an element that’s loading in our JavaScript app, we should make sure the element is present when we’re trying to select it.
To make sure this is the case, we can use document.querySelector
in the DOMContentLoaded
event listener.
For instance, if we have:
<input id="tags">
then we can write:
document.addEventListener("DOMContentLoaded", () => {
document.querySelector('input')
.addEventListener('change', (event) => {
//...
})
});
to select the input in the DOMContentLoaded
event handler.
We add the event handler with the document.addEventListener
method to listen to the event emitted by the html
element.
Then we make sure that the input element is already loaded by putting the document.querySelector
call inside the DOMContentLoaded
event handler.
Conclusion
To fix the JavaScript ‘document.querySelector(…) is null’ error when we try to select an element that’s loading in our JavaScript app, we should make sure the element is present when we’re trying to select it.
To make sure this is the case, we can use document.querySelector
in the DOMContentLoaded
event listener.