1

I have an array that has the names of people. I want to use this array to cycle through every single person in the array and make a button with the name. That button will then get to console.log the name of the person. The problem here is that I don't think I can use onClick in a template string lateral.

Here's something that it looks like.

let content = document.getElementById("content")
var array = ["John", "Adam", "Sid", "Edward"]

array.forEach(element => {

  function runEvent() {
    console.log(element)
  }
  content.innerHTML += `<button onclick="runEvent()">${element}</button>`
})
<div id="content">
</div>

How do I do this?

  • See [here](https://stackoverflow.com/a/59539045) - inline handlers may only reference global variables, but `runEvent` isn't global. Best solution: avoid the inline handler entirely. Create/Append the element with `createElement` and `appendChild`, and use `addEventListener` on it to attach the listener – CertainPerformance Jan 12 '21 at 00:49

1 Answers1

0

here we go, just add the event it self to the button onclick event check the snippet

let content = document.getElementById("content")
var array = ["John", "Adam", "Sid", "Edward"]

array.forEach(element => {

  content.innerHTML += `<button onclick="console.log('${element}')">${element}</button>`
})
<div id="content">
</div>
Burham B. Soliman
  • 1,380
  • 1
  • 9
  • 13