Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

98
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda