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

for loop

Hi All,

Could someone explain the following please?

The message im receiving is: Uncaught TypeError: Cannot set property 'innerHTML' of null

(I have created a div called test in my html)

Thanks

var Player =function (name,position) { this.name=name; this.position=position

}

var vardy= new Player ("vardy","forward"); var kasper = new Player ("kasper","goalkeeper")

var arr=[]; arr.push(vardy); arr.push(kasper);

var text="";

for(var i=0;i<arr.length;i++) {

text+= "names "+arr[i].name;

}

document.getElementById("test").innerHTML=text;

2 Answers

Maybe try storing document.getElementById('test') in a variable: var test = document.getElementById('test'); Then change the innerHTML of test via test.innerHTML = text;

I don't have your HTML so I couldn't test myself but I did get the function to change the html of a blank page by doing the above to the selector 'document.getElementsByTagName('body')[0]'. Hope this helps

It could also be that the element you are trying to select hasn't loaded in the DOM. Make surethe <script> tag is placed above the closing </body> tag in the html.

Always something so simple ha! I had my script in the head section, as John Reardon said, it hadn;'t loaded in the DOM. Many thanks for your help

It's common to keep JS after the footer for this exact reason.