Home > Mobile >  How do I add a delete button next to my task list?
How do I add a delete button next to my task list?

Time:10-25

This is what i have right now, what code do i add to make buttons next to my tasks, so with every new task there must come a remove button as well

document.getElementById('submit').addEventListener('click', withClick);

function withClick(e) {
  const li = document.createElement('li')
  document.getElementById('listid').appendChild(li);
  li.appendChild(document.createTextNode(document.getElementById("text-area").value))
  li.id = 'list'
  li.className = 'collection-item'
  const button = document.createElement('button')
  document.getElementById('list').appendChild(button);
  button.appendChild(document.createTextNode('x'))
  button.className = "button"
}
<ul id="listid">
</ul>
<input id="text-area">
<button id="submit">submit</button>

This is what it looks like in browser

CodePudding user response:

id needs to be unique in HTML.

Currently every <li> element you create has id="list". So when you do this:

document.getElementById('list')

Which one do you expect it to find and why? The behavior is likely undefined, but what you're observing is that it finds the first one with that id and then stops searching. Because why wouldn't it? Once it finds the element with the target id, as far as the browser is concerned it has found the one target element you're looking for.

Instead of fetching the element by its id, you already have a reference to it in the li variable. Just use that:

document.getElementById('submit').addEventListener('click', withClick);

function withClick(e) {
  const li = document.createElement('li')
  document.getElementById('listid').appendChild(li);
  li.appendChild(document.createTextNode(document.getElementById("text-area").value))
  li.className = 'collection-item'
  const button = document.createElement('button')
  li.appendChild(button); // <---- here
  button.appendChild(document.createTextNode('x'))
  button.className = "button"
}
<ul id="listid">
</ul>
<input id="text-area">
<button id="submit">submit</button>

  • Related