How do I update the innerHTML of a div with the contents of a JS array after pushing new items into it?

I have an array with three items in it, and four buttons – each adds a new item to the array.

Pushing items into the array with the buttons is working fine, but, as for the div where the items are displayed, it does not update correctly. The first item I push always shows up on the div correctly, but from there on, everytime I click on one of the remaining buttons, the same items shows up.

What am I doing wrong here?

JSFiddle

var inventory = ["Apple", "Pear", "Orange"];

for (i = 0; i < inventory.length; i++)
  document.getElementById("arrayDiv").innerHTML += inventory[i] + "<br>";

function addItem(newItem, itemBtn) {
  inventory.push(newItem);
  document.getElementById(itemBtn).style.display = "none";
  console.log(inventory);
  document.getElementById("arrayDiv").innerHTML += inventory[i] + "<br>";
}
<p>Fruits:</p>
<div id="arrayDiv"></div>
<hr>
<input id="banana" type="button" value="Banana" onclick="addItem('Banana', 'banana')">
<input id="melon" type="button" value="Melon" onclick="addItem('Melon', 'melon')">
<input id="pineapple" type="button" value="Pineapple" onclick="addItem('Pineapple', 'pineapple')">
<input id="coconut" type="button" value="Coconut" onclick="addItem('Coconut', 'coconut')">

1 thought on “How do I update the innerHTML of a div with the contents of a JS array after pushing new items into it?”

  1. var inventory = ["Apple", "Pear", "Orange"];
    
    for (i = 0; i < inventory.length; i++)
      document.getElementById("arrayDiv").innerHTML += inventory[i] + "<br>";
    
    function addItem(newItem, itemBtn) {
       
      inventory.push(newItem);
      document.getElementById(itemBtn).style.display = "none";
      
      document.getElementById("arrayDiv").innerHTML += newItem + "<br>";
    }
    <p>Fruits:</p>
    <div id="arrayDiv"></div>
    <hr>
    <input id="banana" type="button" value="Banana" onclick="addItem('Banana', 'banana')">
    <input id="melon" type="button" value="Melon" onclick="addItem('Melon', 'melon')">
    <input id="pineapple" type="button" value="Pineapple" onclick="addItem('Pineapple', 'pineapple')">
    <input id="coconut" type="button" value="Coconut" onclick="addItem('Coconut', 'coconut')">
    Reply

Leave a Comment