Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading