0

I have a table on my web page that I wish to change using JavaScript. My main goal is to add 2 TD to a new row. Somehow after running my code a new row is inserted but all the data is in on TD, why?

var table2 = document.getElementById("testsPieArea");
var rowCounter = table2.rows.length;
var i;
for (i = 0; i < 2; i++) {
  var row = table2.insertRow(rowCounter);
  var cell1 = row.insertCell(0);
  var cellData = "<tr>";
  cellData += "<td> Info1 </td><td> Info2 </td></tr>";
  cell1.innerHTML = cellData;
  rowCounter++;
}

In real life is see 2 rows being created but "info1info2" is written in them and that's not what I asked for.

1
  • Include a full; working example. Also, where are your using i? Commented Mar 9, 2020 at 11:34

2 Answers 2

1

cell1 (created by HTMLTableRowElement.insertCell()) refers to a cell (td), not row. You should insert into row:

row.innerHTML = cellData;

var table2 = document.getElementById("testsPieArea");
var rowCounter = table2.rows.length;
for (var i = 0; i < 2; i++) {
  var row = table2.insertRow(rowCounter);
  var cellData = "<tr><td> Info1 </td><td> Info2 </td></tr>";
  row.innerHTML = cellData;
  rowCounter++;
}
table, td {
  border: 1px solid black;
}
<table id="testsPieArea"></table>

Sign up to request clarification or add additional context in comments.

Comments

0

If you want to add a new row, with two values, you can create the elements and set their textContent before adding them as children.

insertRow(document.querySelector('#my-table'), [ 'A', 'B' ]);

function insertRow(table, data) {
  let tbody = table.querySelector('tbody'),
      tr = document.createElement('tr');
  data.forEach(value => {
    let td = document.createElement('td');
    td.textContent = value;
    tr.appendChild(td);
  });
  tbody.appendChild(tr);
}
table {
  border-collapse: collapse;
}

table,
th,
td {
  border: thin solid grey;
}

th,
td {
  text-align: center;
  padding: 0.25em;
}
<table id="my-table">
  <thead>
    <tr>
      <th>Col 1</th>
      <th>Col 2</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Row 1, Col 1</td>
      <td>Row 1, Col 2</td>
    </tr>
  </tbody>
</table>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.