How do i add a column to my HTML Table using JavaScript

I am trying to add to my HTML table using JavaScript.
what I want is to have an added column to the lines that the answer (3rd Column) is not correct. This column needs the proper answer and it needs the background to be changed.

<!doctype html>
	<title>Jasmine Lusty Assignment 4</title>
		html, body {
		  font-family: arial;
		table {
		  border-collapse: collapse;
		  width: 80%;
		  margin: 1em;
		td,th {
		  border: solid grey 1px;
		  padding: 5px;
		th {
		  background-color: #7fffd5;
		td {
		  text-align: center;
		.badAnswer {
		  background-color: #f47c6f;

<!-- Math ---->
		<table id='table-math'>
			  <th> 1st Number </th>
			  <th> 2nd Number </th>
			  <th> Answer </th>
				<tr> <td>5</td> <td>3</td> <td> 8</td>  </tr>
				<tr> <td>7</td> <td>6</td> <td>13</td> </tr>
				<tr> <td>5</td> <td>5</td> <td>10</td>  </tr>
				<!-- Needs Proper Answer (11) --->
				<tr> <td>8</td> <td>3</td> <td>13</td> </tr>
				<tr> <td>4</td> <td>7</td> <td>11</td> </tr>
				<tr> <td>3</td> <td>9</td> <td>12</td>  </tr>
				<!-- Needs Proper Answer (13)--->
				<tr> <td>8</td> <td>5</td> <td>12</td> </tr>
				<tr> <td>2</td> <td>6</td> <td> 8</td>  </tr>
				<tr> <td>5</td> <td>9</td> <td>14</td> </tr>
				<tr> <td>6</td> <td>6</td> <td>12</td>  </tr>
	<script language="javascript" type="text/javascript">
		const tableMath = document.getElementById('table-math');

	for (let line=1; line < tableMath.rows.length; line++)
	  if ( tableMath.rows[line].cells[2].textContent != tableMath.rows[line].cells[3].textContent )

Thanks for the Help!

HTML doesn’t allow you to have non-box grids, so add another td element to every row, and only fill them in when they are incorrect.

1 Like

If I add the other HTML column in is there a way to do the math between column 1 and column 2 to see if they match column 2 and add in the data to the 4th column if they don’t add up to the 3rd column?

Yes there is. You can loop through each row, and do that quite easily.

1 Like

How would you recommend doing that?

By using querySelectorAll to get the rows, forEach to loop through each of them, and the cells property to work with the different table data cells in the row.

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