code-8
code-8

Reputation: 58652

How can I print out Javascript data into HTML DOM?

I'm trying to print out a JS data into an HTML DOM. I couldn't get it to print. What did I do wrong ?

<!DOCTYPE html>
<html>

    <head>
        <title>JSON</title>
        <script type="text/javascript">
            // user is the property of obj1
            var obj1 = {
                user: "John",
                age: 26,
                country: "United States"
            };
            document.getElementById("results").innerHTML = obj1.user + "<hr>";
        </script>
    </head>

    <body>
        <div id="results"></div>         <---- Expected to see John HERE
    </body>

</html>

In my console

Uncaught TypeError: Cannot set property 'innerHTML' of null

Here is my JSFiddle

Upvotes: 1

Views: 297

Answers (3)

Saumil
Saumil

Reputation: 2517

The reason you are getting the error is because you have specified the script within the head section and so the script is executed before the HTML element with id="results" is created

Instead of importing the script in the head section, import it just before the closing body tag </body>

    <body>
        <div id="results"></div>         <---- Expected to see John HERE
        <script type="text/javascript">
            // user is the property of obj1
            var obj1 = {
                user: "John",
                age: 26,
                country: "United States"
            };
            document.getElementById("results").innerHTML = obj1.user + "<hr>";
        </script>
    </body>

Upvotes: 1

chris97ong
chris97ong

Reputation: 7060

The div with the Id of results has not loaded when the document.getElementById("results").innerHTML = obj1.user + "<hr>"; in the Javascript was called.

So window.onload can be used to only execute the Javascript code when the document is loaded.

<!DOCTYPE html>
    <html>
    
        <head>
            <title>JSON</title>
            <script type="text/javascript">
                // user is the property of obj1
                window.onload = function() {
                    var obj1 = {
                        user: "John",
                        age: 26,
                        country: "United States"
                    };
                    document.getElementById("results").innerHTML = obj1.user + "<hr>";
                }
            </script>
        </head>
    
        <body>
            <div id="results"></div>         <---- Expected to see John HERE
        </body>
    
    </html>

Another way is to put the script tag (without the window.onload, as in the OP's post) behind <div id="results"></div>, so that the div is loaded before the JavaScript code is executed.

Upvotes: 1

code-8
code-8

Reputation: 58652

There might be more than 1 way to solve this, but I solve mine by wait for the window to load:

window.onload = function()
{
    // my JSCodeHERE
}

Upvotes: 1

Related Questions