0

I am rendering some HTML elements using an array but when it comes to adding an event listener and passing relative arguments to it I appear to lose my binding and am unsure how to get it back. In my example below when I click on a rendered Div it gives me an alert of 'undefined'. Any help appreciated!

const results = [{
    name: 'john',
    surname: 'smith'
  },
  {
    name: 'jake',
    surname: 'brown'
  }
]
// create a div element for each item in array
results.forEach((result) => {
  const resultDiv = document.createElement('div')
  resultDiv.textContent = result.name
  resultDiv.addEventListener('click', (result) => {
    alert(result.surname)
  })
  document.querySelector('#results-area').appendChild(resultDiv)
})
<div id="results-area"></div>
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
CAF
  • 13
  • 3
  • You defined two `result` variables - one is in the `forEach` callback (which you want), the other is in the `addEventListener` callback (which you *don't* want). Remove the `addEventListener` parameter so that `result` will reference the outer variable – CertainPerformance Mar 04 '20 at 05:38
  • Sorry, so if i remove the addeventlistener how do i create an on click event that can reference the name or surname variable? Thats my goal - to have a click do something with the results array – CAF Mar 04 '20 at 05:54
  • I said to remove the *parameter*, not the whole function (you need the function, of course) – CertainPerformance Mar 04 '20 at 05:54
  • Now i get you. Sounds pretty elementary really! Thanks – CAF Mar 04 '20 at 06:05

0 Answers0