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

151
Visualizações
List of objects Click event

I want to display and click objects in a html list on my webpage. The creation of the html list including the object values (name) works well, also the click event. But I can not get the clicked object value (e.g. name). The result:

(e.target.id) is ''(empty).

//Array of objects
let tierArray = {
  "name": data.Name,
  "geburtstag": data.Geburtstag,
  "geschlecht": data.Geschlecht,
  "idNummer": data["ID Nummer"],
  "imageIndexPath": data["Image Index Path"],
  "information": data.Information,
  "rasse": data.Rasse,
  "tierart": data.Tierart,
  "imTierheimSeit": data["im Tierheim seit"]
}

listOfTierObjects.push(tierArray);

//this works
for (let i = 0; i < listOfTierObjects.length; i++) {
  let row = `${listOfTierObjects[i].name}`;
  document.getElementById("tiereList").innerHTML += '<li>' + row + '</li>';
};

//The problem is here
document.getElementById("tiereList").onclick = function(e) {
  console.log(e.target.id);
}
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You aren't putting any id on the li, so e.target.id is "".

You haven't said what value you want to put there, but for instance you could put the index there if you wanted:

document.getElementById("tiereList").innerHTML += '<li id="' + index + '">' + row + '</li>';

...though I think I'd use a data-* attribute instead.

(Note: Someone might tell you that id="1" [for example] isn't valid, but that's a common myth. An id can be anything you want as long as it's unique and doesn't have any whitespace. The myth comes from the fact that a CSS ID selector can't start with an unescaped digit. But again, I wouldn't use id for this [what if you do this in two places?]. I'd use ...data-index="' + index + '"... and getAttribute("data-index"0 instead.)


A couple of side notes:

  • Using += on innerHTML is not best practice. Either build up the full string in a variable and make a single assignment to innerHTML, or use insertAdjacentHTML, or use createElement instead.
  • Even though getElementById is very fast, if you're going to use it in a loop for the same element, it's probably clearer to grab it to a variable and reuse the variable.
  • let row = `${listOfTierObjects[i].name}`; when listOfTierObjects[i].name is a string can more simply be written let row = listOfTierObjects[i].name;.
  • Rather than assigning to .onclick, I would suggest using addEventListener.
  • Your current click handler will work, but if you had any child elements inside the li it wouldn't work reliably. Instead, use const li = e.target.closest("li"); to reliably get the li element, even if the click is on a child element within the li.

More:

  • data-* attributes
  • addEventListener
  • closest
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