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>
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>
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);
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With