This question has already been answered:

I just learn how to typeset websites and sometimes I encounter such a problem that when I try to add a function to an element (not just a function, I mean working with JS in general), I get the error "Cannot read property" in my browser console (usually Chrome), for example: enter image description here

The rest of the code in the githabe branch body-wr
PS I'm a little dumb

Reported as a duplicate at Grundy. javascript Mar 3 at 9:09 pm

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

  • Connect the script to the end of the body . - meine

2 answers 2

Since the browser processes the html-page strictly from top to bottom, when inserting the script you need to be sure that the elements you are accessing will be available at the time the script is executed.

There are two ways:

  1. Place script tags that work with the dom-tree ( read: elements ) at the very bottom of the page, namely, before </body>

  2. You can post anywhere, but the code that works with elements can only be called when DOMContentLoaded or load events DOMContentLoaded , for example:

     window.addEventListener('DOMContentLoaded', function() { // Ваш код }); 

In general, the universal way of placing resources on the page is when the styles are at the top, at the head , and the js code is at the bottom.

There are several reasons:

  1. Styles are loaded before the page is displayed and the page will be immediately displayed with the styles. What will happen otherwise, you will understand simply by turning off the styles on the page
  2. The javascript code needs to be loaded and executed, this may cause an additional delay.
  3. Your case: when the item is not there yet, but the code is looking for it.

Here's a great javascript site , “go through” it and save yourself a lot of time.

    If I understand correctly, your script is placed in the head and is triggered before the body becomes part of the DOM - so the element is not found, null returned instead of it, which does not have the mentioned property.

    Several outputs are possible: wrap the code in a function and assign its execution to the onload your body ; or insert a script element at the end of the body ; or assign an onclick handler in the code of the div element itself.