Is it possible to add an eventListener in a for loop, if so, how would you implement it?

For me For Loops and ForEach Loops are two of the best ways to handle and display large data. The issue is I want to add an eventListener to a loop and you immediately run into issues. Here is my code, it loops through an API Provided Array and creates HTML Divs perfectly. Near the bottom of the code you can see me attempting to add an EventListener and log any click that occurs. When I click I receive this in the console:

[object HTMLDivElement] Has Been Clicked

Which means it isn’t pulling information from the clicked div.

for (i = 0; i < filtered.length-1; i++) {
   //Loop through games of Leagues

   for (x=0; x<filtered[i].length;x++){
    //Create Parent Div For Data
let parent = document.createElement("div")
parent.className = 'parentDiv'

//League Duplication not allowed
if (arrLeagues.includes(filtered[i][x] {

} else {

//League Name
let league = document.createElement("div")
league.className = 'league'
league.innerHTML = filtered[i][x] + `<img class='flag' src=${filtered[i][x].league.flag}>`

//Home Container
let child1 = document.createElement("div")
child1.className = 'childDiv'

//Game Status
let gameStatus = document.createElement("div")
gameStatus.className = 'status'
gameStatus.innerHTML = filtered[i][x].fixture.status.short

//Home Name
let homeTeamName = document.createElement("div")
homeTeamName.className = 'team1'
homeTeamName.innerHTML = filtered[i][x]

//Home Score
let homeTeamScore = document.createElement("div")
homeTeamScore.className = 'score1'


//Away Container
let child2 = document.createElement("div")
child2.className = 'childDiv'

//Away Name
let awayTeamName = document.createElement("div")
awayTeamName.className = 'team2'
awayTeamName.innerHTML = filtered[i][x]

//Away Score
let awayTeamScore = document.createElement("div")
awayTeamScore.className = 'score2'


//My Attempt to add Event Listener

parent.addEventListener("click", function(){
    console.log(`${awayTeamName} Has Been Clicked`)

//Push all Data to DOM

I have tried looking for other pages or information on this and there does not seem to be a whole lot. If you could link me to information on this or explain how to add eventListeners to loop-created elements that would be nice. Of course I do not even know if this is possible or practical, if it is impossible or impractical don’t be afraid to tell me.

>Solution :

It is possible, though you have to be careful with scopes. let and const mostly solve these problems for for loops though.

In your case, it appears you which to output the content of the div, not the object itself, which you can do with awayTeamName.innerHTML (HTML) or awayTeamName.innerText (text content).

Leave a Reply