Search code examples
javascripthtmldomhtml-tablecreateelement

Creating a table dynamically and the rows are inside the first column


I'm trying to create a table dynamically but after create all the tbody rows are inside the first column.

When I inspect the HTML generated looks good, but the browser is rendering it diferent. What I'm doing wrong?

Something like that:

Id Name Age City
1 Brendon 25 Toronto
2 John 23 Vancouver

And the expectation is:

Id Name Age City
1 Brendon 25 Toronto
2 John 23 Vancouver

The HTML:

<table id="myTable"></table>
<button onclick="createClickHandle()">Create</button>

And the JavaScript:

const dataTest = [
  {
    id: 1,
    name: "Brendon",
    age: 25,
    city: "Toronto"
  },
  {
    id: 2,
    name: "John",
    age: 23,
    city: "Vancouver"
  }
];

const createNewTable = (tableObject) => {
  const tableId = tableObject.tableId;
  const data = tableObject.data;
  const header = Object.keys(data[0]);

  createHtmlTable(tableId, header, data);
  
};

const createHtmlTable = (id, header, data) => {
  const htmlTable = document.getElementById(id);

  //create the thead
  createHeader(htmlTable, header);

  //create the tbody
  createBoby(htmlTable, header, data);
};

const createHeader = (table, columns) => {
  const thead = document.createElement("thead");
  const tr = document.createElement("tr");

  columns.forEach((element) => {
    const th = document.createElement("th");
    th.appendChild(document.createTextNode(element));
    tr.appendChild(th);
  });

  thead.appendChild(tr);
  table.appendChild(thead);
};

const createBoby = (table, header, data) => {
  const tbody = document.createElement("tboby");
  
  data.forEach((element) => {
    const tr = document.createElement("tr");

    header.forEach((headerItem) => {
      const td = document.createElement("td");
      td.appendChild(document.createTextNode(element[headerItem]));
      tr.appendChild(td);
    });
    
    tbody.appendChild(tr);
  });

  table.appendChild(tbody);
};

const createClickHandle = () => {
  createNewTable({
    tableId: "myTable",
    data: dataTest,
  });
};

Solution

  • You seem to have a typo "tboby" in a few locations.

    The one that may be causing the issue is here:

    const tbody = document.createElement("tboby");
    

    Your trying to create a tboby element which is not a valid HTML element.

    Try updating to this:

    const tbody = document.createElement("tbody");