www.webdeveloper.com
Results 1 to 4 of 4

Thread: getting a type error on script to write text to html element, why?

  1. #1
    Join Date
    Mar 2014
    Posts
    2

    getting a type error on script to write text to html element, why?

    Newb here baffled as to why this doesn't work:

    Code:
    <!DOCTYPE html>
    
    <html>
    <head>
        <title>Page Title</title>
        <script type = "text/javascript">
            var foo = document.getElementById("foo");
            foo.innerHTML = "Stuff added by Javascript.";
        </script>
    </head>
    
    <body>
    
        <div id="foo"></div>
    
    </body>
    </html>

  2. #2
    Join Date
    Mar 2014
    Posts
    2
    The error is "TypeError: foo is null" and triggered by the line

    Code:
    foo.innerHTML = "Stuff added by Javascript.";

  3. #3
    Join Date
    Oct 2013
    Posts
    490
    HTML Code:
    <!DOCTYPE html>
    
    <html>
    <head>
        <title>Page Title</title>
        <script type = "text/javascript">
        function foo(){
            var bar = document.getElementById("foo");
            bar.innerHTML = "Stuff added by Javascript.";
        }
        </script>
    </head>
    
    <body onload="foo()">
    
        <div id="foo"></div>
    
    </body>
    </html>

  4. #4
    Actually you are trying to access a property of an element that is not yet created. Make sure the page is completely loaded and all elements are created.

    Here is another approach

    <!DOCTYPE html>

    <html>
    <head>
    <title>Page Title</title>
    <script type = "text/javascript">
    window.onload = function (){
    var foo = document.getElementById("foo");
    foo.innerHTML = "Stuff added by Javascript.";
    }
    </script>
    </head>

    <body>

    <div id="foo"></div>

    </body>
    </html>

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles