Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

109
Views
Event target only targeting first item in loop from localstorage

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);
}
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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);
}

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!