I am trying to make a class that creates a list element while attaching an event listener to it. The following is my code:
class listItem {
constructor(id) {
this.id = id;
this.li = $("<li>");
this.li.text(this.id);
// Selector
this.li.on("click", function() {
this.li.text("clicked");
});
}
getDom() {
return this.li;
}
}
I invoke this class using the following:
// Creating a new listElement and appending it to the list
var l1 = new listItem(1);
$("ul").append(l1.getDom());
However, when I click on the element, I get the following error message:
Uncaught TypeError: Cannot read property 'text' of undefined
at HTMLLIElement. ((index):56)
at HTMLLIElement.dispatch (jquery.js:5206)
at HTMLLIElement.elemData.handle (jquery.js:5014)
Here is my jsfiddle of the code.