Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript JavaScript Loops, Arrays and Objects Tracking Data Using Objects The Build an Object Challenge, Part 2 Solution

Tony E
Tony E
5,802 Points

Why does my code only work with document.write?

This is how I solved the problem, and although it's probably not great, it does seem to work. But if I use the 'getElementById' print function, only the last student entry appears. I was just wondering why one print method works but the other doesn't.

function print(message) {

for ( i = 0 ; i < students.length; i +=1 ) {
 var record = "<h2>Student name: " + students[i].name + '</h2>';
  record += '<p>' + 'Track: ' + students[i].track + '<br>'; 
  record += 'Achievements: ' + students[i].achievements + '<br>';
  record += 'Points: ' + students[i].points + '</p>';


2 Answers

There are several issues here.

First, getElementById() isn't a print function. It's telling the print() function where to place the output on the page, viz., as the innerHTML of the element whose id is output.

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

This function is called after the for loop, and passed a message created in the for loop:

for (var  i = 0; i < students.length; i += 1) {
    student = students[1];
    message += '<h2>Student: " + student.name + '</h2>';
    message += '<p>Track: " + student.track + '</p>';
    message += '<p>Points: " + student.points + '</p>';
    message += '<p>Achievements: " + student.achievements + '</p>';

In your for loop you write over the record for the previous student with each new student, and call the print() function from within the loop. That could work, but each time you call the print() function you were writing to the same element's innerHTML. That's why you had to modify the print() function. But if you create the full message and then call the print() function outside the for loop, it will all come together.

Happy coding.

Tony E
Tony E
5,802 Points

Thank you, sir.