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 Multiple Items with Arrays Build a Quiz Challenge, Part 2 Solution

Marvin Benno
Marvin Benno
7,524 Points

What is wrong with my code?

So i'm trying to make this quiz part 2 and I get the error:

javascript.js:26 Uncaught TypeError: Cannot set property 'innerHTML' of null at print (javascript.js:26) at javascript.js:48

Something seems to be wrong with my .innerHTML. I can't understand what the problem is. Thankfull for feedback!

          <!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Shaba</title>
</head>

<body>
<h1>
This is my Javascript site.
</h1>
<script src="javascript.js" type="text/javascript"></script>
<div id="output">

</div>
</body>
</html>
var arr = [
    ["hur lång är Marvin Benno? ", "190cm"],
    ["Är Putin och McGregor vänner? ", "ja"],
    ["Hur många dagar finns på ett år? ", "365"],
    ["Vart fiskar Marvin gädda? ", "mälaren"],
    ["1?", "2"]
];
var questionsAsked = 0;
var wrong = 0;
var right = 0;
var answer;
var html;
var htmlRight = "<div> <h1> You got these questions right </h1> <ol>";
var htmlWrong = "<div> <h1> You got these questions wrong </h1> <ol>";
var questionsRight = [];
var questionsWrong = [];

function print(message){
    var outputDiv = document.getElementById('output');
    outputDiv.innerHTML = message;
}


for (var i = 0; i < arr.length; i++) {
    answer = prompt(arr[i][0]);
    questionsAsked += 1;

    if (answer.toLowerCase() === arr[i][1]) {
        right += 1;
        questionsRight.push(arr[i][0]);
        htmlRight += "<li>" + questionsRight[i] + "</li>";
    }
    else {
        wrong += 1;
        questionsWrong.push(arr[i][0]);
        htmlWrong += "<li>" + questionsWrong[i] + "</li>";
    }
}
htmlRight += "</ol> </div>";
htmlWrong += "</ol> </div>";
html = "You got " + right + " out of " + questionsAsked + " answered correct.";
print(html);
print (htmlRight);
print (htmlWrong);

1 Answer

Try putting the script tag right before the closing body tag. It looks like it's trying to find the div, but it can't. If you let the browser render your div and then run the js code, you should be good.

Marvin Benno
Marvin Benno
7,524 Points

Well done bro, thanks!