How do I loop through an array on an html table?

I’m trying to show in an HTML table a person’s age and grade. I was able to loop through and find the persons grade without displaying on a table. Im able to get my array on the table but when I try and loop through to find the persons grade it doesn’t work?

		<!DOCTYPE html>
		<html>
		  <head>
			<title>
			  Javascript array to table
			</title>
			<style>

			  html, body {
				font-family: arial;
			  }
			  table {
				border-collapse: collapse;
			  }
			  table tr td {
				border: 1px solid #000;
				padding: 10px;
			  }

			</style>
		  </head>
		  <body>
			  <script>

			 window.addEventListener("load", function(){

		  var grade = [['Age','Grade'],
						[6,'Grade 1'],
						[7,'Grade 2'],
						[8,'Grade 3'],
						[9,'Grade 4'],
						[10,'Grade 5'],
						[11,'Grade 6'],
						];
var html = "<table>";
for (var i = 0; i < grade.length; i++) {
  html += "<tr>";
  for (var j = 0; j < grade[i].length; j++) {
    html += "<td>" + grade[i][j] + "</td>";
  }
  html += "</tr>";
}
html += "</table>";

				 let yourGrade = grade.find(e => {
					return e[0] == grade});
						function changecolors(){
						var a1 = document.getElementById ("gradeTable");
						var a1Legnth = a1.legnth;
						for (var i = 0; i < a1Legnth; i++){
							a1[i].style.background= "#aaabba";
						}
						};


		  // Attach HTML to container
  document.getElementById("container").innerHTML = html;
		});


			  </script>
			<!-- ALL YOU NEED IS A CONTAINER -->
			<div id="container"></div>
		  </body>
		</html>

Hi,

I was answering your other question when it got deleted, so I’ll post the answer here as it seems related.

Is this what you are trying to do:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Javascript array to table</title>
    <style>
      html, body {
        font-family: arial;
      }
      table {
        border-collapse: collapse;
      }
      table tr td {
        border: 1px solid #000;
        padding: 10px;
      }
    </style>
  </head>
  <body>
    <table>
      <thead>
        <tr>
          <td>Grade</td>
          <td>Age</td>
        </tr>
      </thead>
      <tbody>
      </tbody>
    </table>

    <script>
      const grade = [
        ['Grade 1', 6],
        ['Grade 2', 7],
        ['Grade 3', 8],
        ['Grade 4', 9],
        ['Grade 5', 10],
        ['Grade 6', 11],
      ].reverse();

      const tableBody = document.querySelector('table > tbody');

      grade.forEach((el) => {
        const row = tableBody.insertRow(0);
        const cell1 = row.insertCell(0);
        const cell2 = row.insertCell(1);
        cell1.textContent = el[0];
        cell2.textContent = el[1];
      });
    </script>
  </body>
</html>
1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.