<ul>
<li>Item n.1</li>
<li>Item n.2</li>
<li>Item n.3</li>
</ul>
<button>Add Item</button>
const onRemoveNode = event =>
event.target.remove()
const addListener = element =>
element.addEventListener('click', onRemoveNode)
const listItems = document.querySelectorAll('li')
listItems.forEach(addListener)
const addNewItem = () => {
// Create the DOM elements
// "new Date()"
const text = `New Item ${new Date()}`
const textEl = document.createTextNode(text)
const itemEl = document.createElement('li')
// IMPORTANT:
// the trick is that for each new item that
// we generate, we also need to add the
// event listener, if we want to be able
// to remove it with the click!
//
// See how easy it is?
// Expecially because we have prepared a
// cool elper function that shorten our
// coding!
addListener(itemEl)
// Append the elements to one another
// so to create the correct structure
itemEl.appendChild(textEl)
document.querySelector('ul').appendChild(itemEl)
}
document
.querySelector('button')
.addEventListener('click', addNewItem)
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.