3

I'm used to do this via php but now moving to js (newbie) and I can't see why it doesn't work! Also please any suggestion other than document.write? Because I don't want to delete the html that I would make later. All I wanted is to post js array values into html table. when I write: document.getElementById("demo").innerHTML += '<table><tr><td>'+item +'</td></tr></table>'; it works but creates table everytime which is wrong

<html>
<head>
<style>
table, td {
  border: 1px solid black;
}
</style>
</head>
<body>

<span id="demo"></span>

    
<script>
document.write("<table>");
arrayjs.forEach(myFunction);
document.write("</table>");

function myFunction(item) {
 document.getElementById("demo").innerHTML += '<tr><td>'+item +'</td></tr>';
}

</script>

</body>
</html>
M123
  • 1,203
  • 4
  • 14
  • 31
Yosra MH
  • 129
  • 3
  • 11
  • 1
    You aren't putting the table rows inside of the table. You shouldn't use `document.write` for this, see this answer: https://stackoverflow.com/questions/13741584/what-does-document-write-do – Will Taylor Jan 12 '21 at 09:58
  • @WillTaylor table rows are created depending on foreach loop, I think the table isn't seen outside the loop but I don't know why – Yosra MH Jan 12 '21 at 10:15

3 Answers3

2

Your idea that you should avoid document.write is correct as it's generally considered bad practice and should be avoided where possible. A better approach is to use native methods to create elements and add them to the DOM, such as createElement() and appendChild().

You can use this approach to create a table and a tbody within it. From there the tbody has methods which let you create rows, and from there cells within the rows.

Below is an example of how to do this.

let arrayjs = ['foo', 'bar', 'fizz', 'buzz'];
let container = document.querySelector('#demo');
tableFromArray(arrayjs, container);

function tableFromArray(arr, container) {
  let table = document.createElement('table');
  let tbody = document.createElement('tbody');
  
  container.appendChild(table);
  table.appendChild(tbody)
  
  arr.forEach(item => {
    let tr = tbody.insertRow(tbody.rows.length); // add a new row
    let td = tr.insertCell(tr.cells.length); // add a new cell within the row
    td.textContent = item;    
  });
}
table,
td {
  border: 1px solid black;
}
<span id="demo"></span>
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
  • Thank you, this works but I'm trying to avoid using "cells" also because they look ugly with the double borders lines especially that I have images to insert in some td elements :( – Yosra MH Jan 12 '21 at 10:20
  • 1
    If you're building a table you don't have a choice, you have to use `td` cells. That being said, they can easily be styled, or even removed completely, using CSS – Rory McCrossan Jan 12 '21 at 10:25
  • oh yes that's true! I have posted a new answer with another solution that works but I still your solution is the best way to do it :) – Yosra MH Jan 12 '21 at 12:56
1

Create element using document.createElement instead of document.write.

tab = document.createElement("table")

Then, use this same function to create table elements and add content using textContent. Finally, add new element as child using appendChild

arrayjs.forEach(item => {
  row = document.createElement('tr')
  tableItem = document.createElement('td')
  tableItem.textContent = item;
  row.appendChild(tableItem)
  tab.appendChild(row);
})
wwilkowski
  • 341
  • 4
  • 14
  • Thank you for your answer, yes I think it's better to create elements (it's just that this didn't work for me but you are in the correct way) – Yosra MH Jan 12 '21 at 12:59
0

This also works :)

AS Rory and wwilkowski said, creating elements is the best practise but I tried this and it's working too (so I'm posting to anyone who wants simpler solution, eventhough I didn't understand why we should use an empty string):

    
    <html>
    <head>
    <style>
    table {
      border-collapse: collapse;
    }
      td, th {
      border: 1px solid #999;
      padding: 0.5rem;
      text-align: left;
    }
    </style>
    </head>
    <body>
    
    <div id = "test"> </div>
        
    <script>
    var outputHTML = "";
    var animal =["cat","dog","bird","goat"];
    
    // loop over array and create html string
    outputHTML = "<table>";
    for(var i= 0;i<animal.length;i++){
    outputHTML+= "<tr>";
    outputHTML+= '<td>' + animal[i] + '</td>';
    document.getElementById("test").innerHTML = outputHTML;
    outputHTML+= "</tr>";
    }
    outputHTML+= "</table>";
    </script>
    </body>
    </html> 
Yosra MH
  • 129
  • 3
  • 11