Assume that I have an HTML list <ul>
and I add <li>
items dynamically with JS. So the list becomes like this:
<ul id="parent">
<li> //container
Some text <button>Delete</button>
</li>
</ul>
Here, the <button>
is used to delete the <li>
using JS. I created a class with a delete
method to delete the <li>
when the button is clicked:
class MyObj {
constructor(parent, container) {
this.parent = parent;
this.container = container;
}
delete() {
this.parent.removeChild(this.container);
}
}
And this is the function that is used to create <li>
elements:
function create() {
let container = document.createElement('li');
let deleteContainerBtn = document.createElement('button');
container.innerHTML = "Sometext";
container.appendChild(deleteContainerBtn);
parent.appendChild(container);
const obj = new MyObj(parent, container, deleteContainerBtn);
deleteContainerBtn.onclick = function() {
obj.delete()
};
};
This works fine (I add <li>
containers with function create
as many times as I want and they can be deleted when I click their Delete buttons). How?
When function create
is done executing, isn’t obj
supposed to be deleted? How does it perform the delete
method if it is deleted?