<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, index) => {
  /**
   * SOLUTION:
   * "splice" is the most often used
   * method for removing items from an
   * array.
   *
   * Read this code as: "remove 1 item
   * from todos, starting from 
   * position ${index}"
   */
  todos.splice(index, 1)
  
  renderList()
}

/**
 * SOLUTION:
 * this function is used as callback
 * to a "forEach" instruction.
 * 
 * The good news is that "forEach" provides
 * both the item and its index as
 * arguments to the callback :-)
 */
const appendItem = (item, index) => {
  const el = document.createElement('li')
  const elText = document.createTextNode(item)
  
  /**
   * SOLUTION:
   * we can give an "intermediate function"
   * as event handler, this way we can
   * call "removeItem" and use all the
   * informations (aka: variables) that
   * are available within this
   * function's scope.
   */
  el.addEventListener('click', () => {
    removeItem(item, index)
  })
  
  el.appendChild(elText)
  document.getElementById('list1').appendChild(el)
}

// The code below this poind didn't
// change at all

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()

Run Pen

External CSS

This Pen doesn't use any external CSS resources.

External JavaScript

This Pen doesn't use any external JavaScript resources.