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);
}
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:
+= 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.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;..onclick, I would suggest using addEventListener.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: