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

Joram Livengood
seal-mask
.a{fill-rule:evenodd;}techdegree
Joram Livengood
Full Stack JavaScript Techdegree Student 14,603 Points

New print function is not working with my code

I wrote all of the code during the challenge for the first video, and I got everything to work.

However, I started watching this video and I changed my print function from the document.write method to this innerHtml method, and now it's not printing MOST of my code!

Can anyone see why this might be happening? (note: this code is sloppy)

var questionsList = [ ["What is 2 + 2?", "4"], ["What color is Darci?", "black"], ["What color is Penny?", "brown"] ] var correctScore = 0; var wrongScore = 0; var askQuestion;

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

function printScore() { var correctHeadline = "<p>You got ";

var correctList = "<h2>You got these questions correct:</h2> <ol>"; var wrongList = "<h2>You got these questions wrong:</h2> <ol>";

for (i = 0; i < questionsList.length; i++) { askQuestion = prompt(questionsList[i][0]); askQuestion = askQuestion.toLowerCase(); if (askQuestion === questionsList[i][1]) { correctScore += 1; correctList += "<li>" + questionsList[i][0] + "</li>"; } else { wrongScore += 1; wrongList += "<li>" + questionsList[i][0] + "</li>"; } }

if (correctScore === 0) { correctHeadline = "<p>You should try again.</p>"; correctList = ""; } else { correctHeadline += correctScore + " of the questions right!</p>"; correctList += "</ol>"; }

if (wrongScore === 0) { correctHeadline = "<p>YOU GOT ALL THE QUESTIONS RIGHT!</P>"; wrongList = ""; } else { wrongList += "</ol>"; }

print(correctHeadline); print(correctList); print(wrongList); }

printScore();

1 Answer

Steven Parker
Steven Parker
229,644 Points

The assignment in your "print" function replaces the contents of the "outputDiv" each time you call it.

If you want to accumulate instead of replace, use the addition assignment operator instead:

  outputDiv.innerHTML += message;