Why my button is not showing inside li tag?

I would to add a button (deleteButton) inside a <li></li> created and appended before to the <ol>

My code:

let eventList = [];
const inputBox = document.querySelector('.input-field');
const submit = document.querySelector('.submit');
const itemsList = document.querySelector('.list')

function addEvent() {
  const showEvent = inputBox.value;

  const li = document.createElement('li');
  const deleteButton = document.createElement('button');
  itemsList.appendChild(li);
  li.appendChild(deleteButton);


  eventList.push(showEvent)
  li.textContent = showEvent;
  inputBox.value = '';
}

submit.addEventListener('click', addEvent);
<h1>TO-DO LIST</h1>
<input class="input-field" type="text">
<button class="submit" type="button">ADD TO-DO</button>
<ol class="list"></ol>

The button is not showing at all. What can I do to make it show inside the li element?

>Solution :

Make sure you initialize you stuff, then append stuff later.

Your main issue is this:

li.appendChild(deleteButton);
li.textContent = showEvent;

You are appending the button, then immediately setting the textContent which is overwriting the button you just added.

li.textContent = showEvent;
li.appendChild(deleteButton);

Just make sure to set any text, prior to appending to the same element.

Also, don’t forget to handle deletion from not only your DOM, but the eventList array.

const
  eventList = [],
  inputBox = document.querySelector('.input-field'),
  submit = document.querySelector('.submit'),
  itemsList = document.querySelector('.list');

function addEvent() {
  const
    showEvent = inputBox.value.trim(),
    li = document.createElement('li'),
    deleteButton = document.createElement('button');

  li.textContent = showEvent;
  deleteButton.innerText = 'Delete';
  deleteButton.addEventListener('click', removeEvent); // Add handler

  // Now append everything
  li.appendChild(deleteButton);
  itemsList.appendChild(li);
  eventList.push(showEvent);

  inputBox.value = '';
}

function removeEvent(e) {
  const
    item = e.target.closest('li'),
    index = childIndex(item); // handle duplicate todos
  item.remove();
  eventList.splice(index, 1);
};

function childIndex(element) {
  return [...element.parentNode.children].indexOf(element);
}

submit.addEventListener('click', addEvent);
li button { margin-left: 1rem; }
<h1>TO-DO LIST</h1>
<input class="input-field" type="text">
<button class="submit" type="button">ADD TO-DO</button>
<ol class="list"></ol>

Leave a Reply