TypeError: null is not an object

This error occurs when you read a property or call a method on a null object . That's because the DOM API returns null for object references that are blank. An object is expected somewhere and wasn't provided. So, you will get null is not an object error if the DOM elements have not been created before loading the script. In JavaScript , null is not an object; and won't work. You must provide a proper object in the given situation.

null is not an object

Any JavaScript code which executes and deals with DOM (Document Object Model) elements should execute after the DOM elements have been created. JavaScript code is interpreted from top to down as lay out in the HTML. So, if there is a tag before the DOM elements, the JavaScript code within script tag will execute as the browser parses the HTML page .

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.


The DOMContentLoaded event fires when the initial HTML document has been fully loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading . When the browser initially loads HTML and comes across a script area in the text, it can't continue building DOM .

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.


Javascript addEventListener

The addEventListener() works by adding a function or an object that implements EventListener to the list of event listeners for the specified event type on the EventTarget on which it's called. The DOMContentLoaded event happens on the document object . We must use addEventListener to catch it.

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.
 (C) 2022    Founded by raps mk
All Rights Reserved. All other trademarks are property of their respective owners.
SiteMap  | Terms  | About