Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

103
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda