0

I am currently learning how to make a table from an array, but I have the problem when I get the info from the array, it only comes through document.write

var a1=[1,2,3,4,5];
var a2=[1,2,3,4,5];
var a3=[1,2,3,4,5];
var all= [a1,a2,a3];
for (row=0; row<all.length; row++) {

   for(col=0; col<all[row].length; col++){ 

      document.write(all[row][col] + ";" )

}
document.write("<br>"); }

but when I get the info / data from the array in a certain ID it doesn't work document.getElementById

var a1=[1,2,3,4,5];
var a2=[1,2,3,4,5];
var a3=[1,2,3,4,5];
var all= [a1,a2,a3];
for (row=0; row<all.length; row++) {

   for(col=0; col<all[row].length; col++){ 

      document.getElementById("show").innerHTML=all[row][col] + ";" 

}
document.getElementById("show").innerHTML="<br>"; }
M K
  • 61
  • 6
  • Does this answer your question? [How to append data to div using JavaScript?](https://stackoverflow.com/questions/5677799/how-to-append-data-to-div-using-javascript) – Ivar Jul 07 '21 at 11:07
  • `document.write()` writes additional data to the page, whereas `.innerHTML` sets the content of an element. Every time in your loop you set a value to it, it overwrites the previous value. – Ivar Jul 07 '21 at 11:08
  • `.append()`, `.insertAdjacentHTML()` – Andreas Jul 07 '21 at 11:08
  • You need something like `).innerHTML += all` to **append** content. – Tushar Shahi Jul 07 '21 at 11:09

2 Answers2

0

you can load all html in variable and add to innerHtml

var a1=[1,2,3,4,5];
var a2=[1,2,3,4,5];
var a3=[1,2,3,4,5];
var all= [a1,a2,a3];
var html='';
for (row=0; row<all.length; row++) {
    for(col=0; col<all[row].length; col++){ 
         html+=all[row][col]+';';
     }
        html+="<br>";
}

document.getElementById("show").innerHTML=html;
<div id='show'></div>
  • Can you please fix the indentation (there's a _"Tidy"_ button in the snippet editor). That's not really nice/easy to read. – Andreas Jul 07 '21 at 12:19
0

Here is a one-liner that would do the job:

var all=[[1,2,3,4,5],
         [1,2,3,4,5],
         [1,2,3,4,5]];
document.querySelector("table").innerHTML=
all.map(r=>"<tr><td>"+r.join("</td><td>")+"</td></tr>").join("");
td { border:1px solid gray }
<table></table>
Carsten Massmann
  • 26,510
  • 2
  • 22
  • 43
  • _"Here is a one-liner..."_ - Especially important for beginners... – Andreas Jul 07 '21 at 12:20
  • Well, yes, you could write it in longer verses, but in the end, what I used here are very basic and standard methods like `Array.prototype.map()` and `Array.prototype.join()`, avoiding variable declarations and indexing elements of a two-dimensional array. – Carsten Massmann Jul 07 '21 at 13:07