<h3>Todos:</h3>
<ul id="list1"></ul>
<hr />
<button id="btn1">+ Add new item</button>
// This the initial state of the app
const todos = [
'buy milk',
'clean kitchen',
'learn js',
]
const removeItem = (item) => {
/**
* SOLUTION:
* in case you don't have the item's
* index available, you can calculate
* it based on the content:
*/
const index = todos.indexOf(item)
todos.splice(index, 1)
renderList()
}
// The code below this poind didn't
// change at all
const appendItem = (item, index) => {
const el = document.createElement('li')
const elText = document.createTextNode(item)
el.addEventListener('click', () => {
removeItem(item, index)
})
el.appendChild(elText)
document.getElementById('list1').appendChild(el)
}
const clearList = () =>
document
.querySelectorAll('#list1 *')
.forEach(item => item.remove())
const renderList = () => {
clearList()
todos.forEach(appendItem)
}
const addNewItem = () => {
todos.push(`Item n.${todos.length + 1}`)
renderList()
}
document
.querySelector('#btn1')
.addEventListener('click', addNewItem)
renderList()
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.