Self-Deletion of New Elements in JavaScript
In the previous lesson, we learned how to make elements delete themselves when clicked.
Let's now assume there are initially no elements in the parent:
<div id="parent"></div>
Let's create 9 new paragraphs in a loop, while making sure any paragraph is deleted when clicked on:
let parent = document.querySelector('#parent');
for (let i = 1; i <= 9; i++) {
let p = document.createElement('p');
p.textContent = i;
p.addEventListener('click', function() {
this.remove();
});
parent.appendChild(p);
}
Given the following code:
<ul id="parent">
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
<input type="submit" id="button">
Make it so that when the button is clicked, a new element is added to the list. Make it so that any li is deleted when clicked on. This applies to both the li elements already in the list and new ones created after pressing the button.