TypeError: null is not an object

This error emerges when attempting to access a property or invoke a method on an object that is null. This behavior stems from the DOM API returning null for object references devoid of content. The error occurs when an anticipated object is absent or undefined. Therefore, encountering a "null is not an object" error signifies that the requisite DOM elements were not established prior to the script's execution. It's essential to acknowledge that, in JavaScript, null is not a valid object, necessitating the provision of a valid object for the intended context.

JavaScript code that interacts with DOM (Document Object Model) elements should be executed only after these elements have been created. JavaScript is interpreted sequentially, following the HTML layout from top to bottom. Consequently, if a script tag precedes the presence of DOM elements, the enclosed JavaScript code will be executed as the browser parses the HTML page. Ensuring that JavaScript is situated appropriately in the HTML document is crucial to synchronizing its execution with the availability of DOM elements.

The lifecycle of an HTML page has three important events:

  1. DOMContentLoaded - the browser fully loaded HTML, and the DOM tree is built, but external resources like pictures and stylesheets may be not yet loaded.

  2. load - the browser fully loaded the HTML and also external resources like images and stylesheets.

  3. unload (beforeunload) – the user is leaving the page.

DOMContentLoaded

The DOMContentLoaded event triggers once the primary HTML document has been entirely loaded and parsed, disregarding the completion of loading for stylesheets, images, and subframes. Upon the browser's initial encounter with HTML, if it encounters a script area within the text, it temporarily halts the process of constructing the DOM until the script's execution is complete. This event is designed to facilitate interactions that necessitate access to the DOM's structural content before the entire page, including external resources, has been fully loaded.

How to wait for the DOM ready event in plain JavaScript

You can do so by adding an event listener to the document object for the DOMContentLoaded event.

document.addEventListener('DOMContentLoaded', function(event) { //the event occurred })

addEventListener()


Javascript addEventListener

The addEventListener() function operates by incorporating a function or an object that implements the EventListener interface into the roster of event listeners designated for the specified event type on the specific EventTarget on which the function is invoked. The occurrence of the DOMContentLoaded event is associated with the document object. To capture and respond to this event, it is imperative to utilize the addEventListener() method.

document.addEventListener('DOMContentLoaded',() => { // handle DOMContentLoaded event });
document.addEventListener('load',() => { // handle load event });
document.addEventListener('beforeunload',() => { // handle beforeunload event });
document.addEventListener('readystatechange', () => { // handle readystatechange event });
document.addEventListener('unload',() => { // handle unload event });

In the following example, we can resolve this type of issues by adding an event listener that will notify us when the page is ready. Once the addEventListener is fired, the init() method can make use of the DOM elements.

<!DOCTYPE html> <html> <head> <script type="text/javascript"> function init() { var goBtn = document.getElementById("goBtn"); var inTxt = document.getElementById("inTxt"); goBtn.onclick = function() { var myMsg = inTxt.value; showMessage(myMsg); } } function showMessage(myMsg) { var greeting = "Message : " + myMsg + "!"; document.getElementsByTagName ("h2")[0].innerHTML = greeting; } document.addEventListener('readystatechange', function() { if (document.readyState === "complete") { init(); } }); </script> </head> <body> <h2>Message : </h2> <p id="para">addEventListener() demo...</p> <form> <input type="text" id="inTxt" placeholder="Type your messge" /> <input type="button" id="goBtn" value="Go" /> </form> </body> </html>

Conclusion

The error message "TypeError: null is not an object" indicates an attempt to access properties or methods on a null value, which is not recognized as an object in JavaScript. This error often arises when working with the DOM or objects that haven't been properly initialized.