0

I am trying to clean up my html tables by removing the rows and rows of td's and th's and automate it by using a script.

I found this solution here

    function createTable(tableData) {
  var table = document.createElement('table');
  var tableBody = document.createElement('tbody');

  tableData.forEach(function(rowData) {
    var row = document.createElement('tr');

    rowData.forEach(function(cellData) {
      var cell = document.createElement('td');
      cell.appendChild(document.createTextNode(cellData));
      row.appendChild(cell);
    });

    tableBody.appendChild(row);
  });

  table.appendChild(tableBody);
  document.body.appendChild(table);
}

createTable([["row 1, cell 1", "row 1, cell 2"], ["row 2, cell 1", "row 2, cell 2"]]);

Now, before I try to edit the contents of the cells, I wanted to make sure this would work inside my document by copying and pasting and lo it does not.

Here is the fiddle of the original document: https://jsfiddle.net/frodomeg/5u6czpfa/

And here is the fiddle where I'm trying to place the new script in each of the divs: https://jsfiddle.net/frodomeg/07dbwmy4/2/

As you can see in the second link, what is happening is the output is generating at the bottom of the page rather than in each of the divs. I honestly have no idea what I'm doing wrong as I'm very new to js.

Any thoughts? Thanks

Doodlebug
  • 21
  • 8

1 Answers1

0

the output is generating at the bottom of the page rather than in each of the divs

You said:

document.body.appendChild(table);

… which is the end of the <body> element.

If you want it inside a div, then you need to append it to a div and not to the body.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335