Create table using Javascript

Slightly shorter code using insertRow and insertCell:

function tableCreate() {
  const body = document.body,
        tbl = document.createElement('table');
  tbl.style.width="100px";
  tbl.style.border="1px solid black";

  for (let i = 0; i < 3; i++) {
    const tr = tbl.insertRow();
    for (let j = 0; j < 2; j++) {
      if (i === 2 && j === 1) {
        break;
      } else {
        const td = tr.insertCell();
        td.appendChild(document.createTextNode(`Cell I${i}/J${j}`));
        td.style.border="1px solid black";
        if (i === 1 && j === 1) {
          td.setAttribute('rowSpan', '2');
        }
      }
    }
  }
  body.appendChild(tbl);
}

tableCreate();

Also, this doesn’t use some “bad practices”, such as setting a border attribute instead of using CSS, and it accesses the body through document.body instead of document.getElementsByTagName('body')[0];

Leave a Comment