Reputation: 257
Im trying to attach an event listener to each li
element, but instead I want to attach it to the parent ul
, to avoid confusion, if I remove or add li
elements.
var theParent = document.getElementById("parent-list");
theParent.addEventListener("click", function(e) {
// e.target is the clicked item!
if(e.target && e.target.nodeName == "LI") {
console.log("li has been clicked, cool!");
console.log("is this George or Smith!");
}
});
This works fine. However the way I add my li elements to the parent is by creating a custom object, as I need to hold some state information:
var Person = function(name, favColor){
var elem = document.createElement('li');
theParent.appendChild(elem);
this.name = name;
this.color = favColor;
};
var listItems = [];
listItems.push(new Person("Smith", "blue"));
listItems.push(new Person("George", "red"));
One of the solutions I was thinking is to add state information to the li elements by using data-
attribute, but I feel like thats going to get messy If I am going to have so many properties.
Upvotes: 0
Views: 53
Reputation: 3868
right now your JavaScript object and dom elements are not connected at all. you are just using a JavaScript object to create the dom element. data attribute is a good way to go, you can maybe just have a data attribute with an object index, and save all your objects in a JavaScript array. than on click, retrieve the JavaScript object with the correct index from the array.
Please let me know if this is enough to get you going or you need more.
Upvotes: 1