0

I have 2 items in an array. I want to display them in a div element.

But the div element is only showing the 2nd item [5,6,0,8] of the array.

let myArr = [
  [1, 2, 3, 4],
  [5, 6, 0, 8],
];

for (let i = 0; i < myArr.length; i++) {
  document.getElementById("show").innerHTML = myArr[i];
}

I tried with for each but no luck. However, both items appear on the console log.

Please advise.

Mario
  • 4,784
  • 3
  • 34
  • 50
RajC
  • 1
  • 2
  • 3
    Maybe you meant `+=`? The assignment `=` to `innerHTML` will always overwrite. You could also skip the loop and just do `innerHTML = myArr;` for that matter. – ggorlen Jul 03 '20 at 01:57
  • Is this your homework? bc i saw exact same code yesterday. – Kharel Jul 03 '20 at 02:14

1 Answers1

0
let myArr =[[1,2,3,4], [5,6,0,8]];
for(let i = 0; i < myArr.length; i++){
    for(let j=0;j < 4;j++){
   var node = document.createElement("p"); 
    node.innerHTML = `<p> ${myArr[i][j]}</p>`
   document.getElementById('show').appendChild(node);
      console.log(i,j);
    }
}

You first need to create a element then set the HTML for that element as your value.Then push that into your desired element block by callling appendChild.

Note: AppendChild only accepts an element obj not string

❌ document.getElementById('show').appendChild(<p> ${myArr[i][j]}</p>);

Happy coding