I also want to add - because it’s the result of Google search # 1 for the important error message “TypeError: [x] is null” - the most common reason the JavaScript developer will get this is because they are trying to assign an event handler for DOM element, but the DOM element has not yet been created.
The code is mostly executed from top to bottom. Most developers place their JavaScript in the header of their HTML file. The browser received HTML, CSS and JavaScript from the server; Performs "execution" / rendering of a web page; and it executes JavaScript, but it has not yet deleted the HTML file to “execute” / render the HTML.
To deal with this, you need to introduce a delay before JavaScript is executed, for example, put it in a function that is not called until the browser has "executed" all the HTML code and triggered the "DOM ready" event.
With raw JavaScript, use window.onload:
window.onload=function() {
Use jQuery to use the finished document:
$(document).ready(function() {
This way, your JavaScript will not run until the browser builds the DOM, the HTML element exists (not null :-)), and your JavaScript can find it and attach an event handler to it.
Andrew Koper
source share