-1

I am try to edit the html through Javascript with gdocument.getElementById but I always come across the error: Uncaught TypeError --- Cannot set property 'innerHTML' of null

Here is my very simple code

<html>
    <head>  
        <title>External .js File- Page 3</title>
    </head>

    <body>

        <script language="JavaScript">
        document.getElementById("text").innerHTML = "Hi!";
        </script>

        <article id="text"></article>

    </body>
</html>
Zachooz
  • 535
  • 11
  • 25
  • That's like trying to drink beer from a glass which isn't filled yet – PeeHaa Dec 19 '13 at 23:32
  • you need to wait until the page has loaded, i.e. `window.onload = function() { your code here }` – tckmn Dec 19 '13 at 23:33
  • `
    ` doesn't exist until HTML 5, but `language` was deprecated in HTML 4 and is [obsolete in HTML 5](http://www.w3.org/TR/html5/obsolete.html#attr-script-language). Get rid of the language attribute.
    – Quentin Dec 19 '13 at 23:35
  • Thank you guys you were a lot of help! Lol I thought something in my code was wrong. – Zachooz Dec 19 '13 at 23:36

3 Answers3

2

You are trying to get the element before it exists.

Move the script so it appears after the element.

(Or wrap the code in a function, then bind that function to an event handler like load).

Quentin
  • 800,325
  • 104
  • 1,079
  • 1,205
0

Try:

window.onload = function(){

     document.getElementById("text").innerHTML = "Hi!";

};
Eduardo Stuart
  • 2,679
  • 15
  • 21
0

You execute the script before the element exists. document.getElementById is looking for 'text' but it's not there yet. You must put your script inside window onload event like so:

window.onLoad = function () {
    document.getElementById('text').innerHTML = "Hi";
};
ReX357
  • 1,161
  • 3
  • 18
  • 41