Problem creating buttons through .map loop

Solution 1:

First you should be using for .. of or Array.prototype.forEach because .map builds a new array which you are discarding.

Second, make a createButton function that returns the button so you can store it to a value -

function createButton(item) {
  const itemBtn = document.createElement("button")
  itemBtn.type = "button"
  itemBtn.classList.add("item-add-btn")
  itemBtn.innerText += item.name
  return itemBtn
}

Now you can loop -

for (const item of itemList) {
  // create button reference
  const button = createButton(item)

  // add click handler
  button.addEventListener("click", ...)

  // append button to container
  itemBtnContainer.appendChild(button)
}

Here's a full working demo -

const inventory = []

const itemList = [{id:1,name: "Coke Bottle",quality: "usable"},{id: 6,name: "Pair of Jeans",quality: "pants"}]

function renderInventory() {
  document
  .querySelector("#inventory")
  .textContent = `inventory: ${JSON.stringify(inventory, null, 2)}`
}

function createButton(text, onClick) {
  const e = document.createElement("button")
  e.type = "button"
  e.textContent = text
  e.addEventListener("click", onClick)
  return e
}

function addToInv(item) {
  return event => {
    inventory.push(item)
    renderInventory()
  }
}

renderInventory()

for (const item of itemList)
  document.body.appendChild(createButton(item.name, addToInv(item)))
#inventory {
  padding: 1rem;
  background-color: #eee;
  font-family: monospace;
}
<pre id="inventory"></pre>

Solution 2:

Just add your listener in your loop no ?

itemBtn.addEventListener('click', function(event){
  const elem = event.target;
});

Why global itemBtn ?