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 trialTony E
5,802 PointsWhy 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) {
document.write(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>';
print(record);
}
2 Answers
jcorum
71,830 PointsThere 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>';
}
print(message);
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
5,802 PointsThank you, sir.