Jump to content

innerHTML Expression Help


Recommended Posts

Hi W3, this array-within-array should print out Students 1, 2, 3 and their averaged grades, but it's only printing out Student 3 & average, and no console errors. It works fine substituting console.log, so the problem is my innerHTML part. Thanks in advance for direction.

document.addEventListener("DOMContentLoaded", function(){var grades = [[89, 77, 78], [76, 82, 81], [91, 94, 89]];var total = 0;var average = 0.0;for (var row = 0; row < grades.length; row++){    for (var col = 0; col < grades[row].length; col++){    total += grades[row][col];}    average = total / grades[row].length;    divid = document.getElementById("nice");    divid.innerHTML = 'Student ' + parseInt(row+1) + 'average: ' + average.toFixed(2);    total = 0;    average = 0.0;}});
Link to post
Share on other sites

It's actually best to try not to modify the DOM inside a loop.

<!DOCTYPE html><html lang="en"><head><meta charset="utf-8"><title>title</title><style>td,th,table{border:1px solid #999;text-align:center;}</style><script>document.addEventListener("DOMContentLoaded", function(){var grades = [[89, 77, 78], [76, 82, 81], [91, 94, 89]];var total = 0;var average = 0.0;var str = '<table><tr><th>Student</th><th>Average</th></tr>';for (var row = 0; row < grades.length; row++){    for (var col = 0; col < grades[row].length; col++){    total += grades[row][col];}    average = total / grades[row].length;    str += '<tr><td>'+ parseInt(row+1) + '</td><td>' + average.toFixed(2) + '</td></tr>';    total = 0;    average = 0.0;}str += '</table>';document.getElementById("nice").innerHTML = str;});</script></head><body><div id="nice"></div></body></html>
Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
×
×
  • Create New...