<h3>Todos:</h3>
<ul id="list1"></ul>
<hr />
<button id="btn1">+ Add new item</button>
/**
* SOLUTION:
* Note that for this solution to work you
* need to make "todos" a variable.
*
* This will not impact this simple app
* so much, but can you find out why it
* would be better to stick to a constant?
*/
let todos = [
'buy milk',
'clean kitchen',
'learn js',
]
const removeItem = (itemToDelete) => {
/**
* SOLUTION:
* you can also rewrite the array
* and filter its contents using a
* custom function.
*
* this is often the go-to methodology
* when you deal with complex data.
*/
todos = todos.filter((item) => {
return item !== itemToDelete
})
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.