Home javascript CANNOT SET PROPERTY OF NULL ERROR

CANNOT SET PROPERTY OF NULL ERROR

Author

Date

Category

until today I never wrote on pure JavaScript’e. But it was impatient. I immediately called the mistake, and what’s wrong – I do not understand.

There is one file (index.html):

& lt;! DOCTYPE HTML & GT;
 & lt; html & gt;
 & lt; Head & gt;
 & lt; Meta http-equiv = "content-type" content = "text / html; charset = utf-8" / & gt;
 & lt; Meta Charset = "UTF-8" / & gt;
 & lt; script src = "script.js" & gt; & lt; / script & gt;
 & lt; / Head & gt;
 & lt; Body & gt;
 & lt; div id = "qwer" & gt; 11 & lt; / div & gt;
 & lt; / body & gt;
& lt; / html & gt;

and second file (script.js):

(function () {
Document.getelementByid ("QWER"). Innerhtml = '44 ';
}) ();

In general, the script does not work, the debugger writes “Uncaught Typeerror: Cannot Set Property of Null”
What is wrong? After all, the element with ID “QWER” exists.


Answer 1, Authority 100%

At the time of the script execution, the document has not yet loaded to the end.

First option.
You need to make an analogue of the JQuery method $ (Document) .ready ().
For example, call your method inside Window.Onload = function () {};
Note that in this way the function to the event can only be mounted once. If there is little – you need to make your cross-browser analogue jQuery method bind.

There is a second option. Move the script call to the bottom of the document.


Answer 2, Authority 40%

(function () {
Window.Onload = FUNCTION {
Document.getelementByid ("QWER"). Innerhtml = '44 ';
}
}) ();

Answer 3, Authority 30%

You can put in the Script Defer tag)


Answer 4, Authority 10%

Just move the script tag to the bottom:

& lt;! DOCTYPE HTML & GT;
 & lt; html & gt;
 & lt; Head & gt;
 & lt; Meta http-equiv = "content-type" content = "text / html; charset = utf-8" / & gt;
 & lt; Meta Charset = "UTF-8" / & gt;
 & lt; / Head & gt;
 & lt; Body & gt;
 & lt; div id = "qwer" & gt; 11 & lt; / div & gt;
 & lt; / body & gt;
 & lt; script src = "script.js" & gt; & lt; / script & gt;
& lt; / html & gt;

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions