Home > database >  Event target only targeting first item in loop from localstorage
Event target only targeting first item in loop from localstorage

Time:10-04

Working on a Spotify app for a practice where I'm storing searched artist object values into localstorage then I want to get the artist name with e.target but it's only logging the first result from localstorage. Why isn't it targeting every element created this way?

for instance, if I've searched and stored 4 artists, it only logs the name of the first object stored.

object.keys(localStorage).forEach((key) => {
  artistObj = JSON.parse(localStorage.getItem(key));
  artistList = document.getElementById("displayResults");
  artistName = document.createElement("a");
  artistResult = document.createElement("li");
  artistName.innerHTML = artistObj[0].items[0].name;
  artistResult.appendChild(artistName);
  artistList.appendChild(artistResult);
});
artistName.addEventListener("click", getRelatedArtists);

function getRelatedArtists(e) {
  console.log(e.target);
}

CodePudding user response:

All you need is to add the event-listener inside the loop to add it for each element

object.keys(localStorage).forEach((key) => {
  let artistObj = JSON.parse(localStorage.getItem(key));
  let artistList = document.getElementById("displayResults");
  let artistName = document.createElement("a");
  let artistResult = document.createElement("li");
  
  artistName.innerHTML = artistObj[0].items[0].name;
  artistResult.appendChild(artistName);
  artistList.appendChild(artistResult);
  artistName.addEventListener("click", getRelatedArtists);
});


function getRelatedArtists(e) {
  console.log(e.target);
}

  • Related