Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript JavaScript Loops, Arrays and Objects Tracking Data Using Objects Accessing Object Properties

Uncaught TypeError: Cannot set property 'innerHTML' of null at print (script.js:29) at script.js:32?

var student={ name:'osnan', age :23, batch:'1511a', skills:['html','css','ms office'], country:'us'

};

function print( message){
var div=document.getElementById('a');
div.innerHTML=message;

    }

print(student.age); //html <!doctype html> <html> <head> <meta charset="utf-8"> <title>Untitled Document</title> <script src="script.js"></script> </head>

<body> <div id="a"></div> </body> </html>

2 Answers

Konrad Traczyk
Konrad Traczyk
22,287 Points

Hello, your script runs before all DOM has been loaded, so basiclly you trying to get element which isn't parsed yet that's why you get error.

Place your script tags after body closing tag thats ensures you that whole document has been already parsed when the script starts executing.

<!doctype html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Untitled Document</title>
    </head>
    <body>
        <div id="a"></div>
    </body> 
    <script src="script.js"></script>
</html>

Hope it helps.

thanks :)

RODRIGO MARTINEZ
RODRIGO MARTINEZ
5,912 Points

Just wanted to say thanks too. As this solution helped me with another project :)

thanks. helped me from pulling my hair out in frustration