Home > Software engineering >  Creating a table with js
Creating a table with js

Time:03-27

OK, I am very new to these things. I thought I got the DOM sense right but my code is not working. The task is to create a table like this

This is the piece I did. Could you please help me out with pointing out at the mistake I made or parts missing in my code? Every help very much appreciated.

const tableValues = new Array(10).fill(false).map((x, i) => {
  return new Array(10).fill(1).map((y, i2) => {
    return (i   1) * i2
  })
})

document.addEventListener('DOMContentLoaded', tableCreate, false);

function tableCreate() {
  const table = document.getElementById("table");
  tableValues.forEach((row) => {
    const row = document.createElement("tr")
    row.forEach(cell => {
        const cell = document.createElement("td");
        cell.innerHTML = cellText;
        cell.appendChild(cellText)
      }
      row.appendChild(cell))
  })
  table.appendChild(body)
}
<table>
  <tbody id="table"></tbody>
</table>

CodePudding user response:

I have fixed your script without changing the code much. Study it and figure out what were the issues

Basically you had the appendChild outside both loops. Also you used appendChild twice on the cell - you COULD have used a createTextNode on the value to use appendChild on the cellcontent

const tableValues = new Array(10).fill(false).map((x, i) => {
  return new Array(10).fill(1).map((y, i2) => {
    return (i   1) * i2
  })
})

document.addEventListener('DOMContentLoaded', tableCreate, false);

function tableCreate() {
  const table = document.getElementById("table");
  tableValues.forEach(values => {
    const row = document.createElement("tr")
    values.forEach(value => {
      const cell = document.createElement("td");
      cell.innerHTML = value;
      //cell.appendChild(cellText)
      row.appendChild(cell)
    })
    table.appendChild(row)
  })
}
<table>
  <tbody id="table"></tbody>
</table>

Here is a shorter version

const tableValues = new Array(10).fill(false).map((x, i) => new Array(10).fill(1).map((y, i2) => (i   1) * i2))


const tableCreate = () => document.getElementById("table")
  .innerHTML = tableValues
    .map(values => `<tr>
      ${values
        .map(value => `<td>${value}</td>`).join('')} 
    </tr>`).join('');


document.addEventListener('DOMContentLoaded', tableCreate);
<table>
  <tbody id="table"></tbody>
</table>

  • Related