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 remove one specific <li> element from html using basic javascript?

I’m trying to make a to-do list.

I’ve managed to make new tasks appear as list elements <li> inside unordered list (with a button next to each element which I want to use to delete this particular element. The problem is, I can’t figure out how to do that. I’ve read about removeChild(), but it seems to only work on first or last element.

let addTaskToTheList = () => {
let task = document.getElementById("task_input_field").value;
let list = document.getElementById("to-do_list");
    list.innerHTML += `<li>${task}</li><button type="button"onclick="deleteTask()">X</button>`
}

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 :

Select the correct li element using event.currentTarget.closest("li") and remeve it from the selector.

Working Fiddle

let addTaskToTheList = () => {
  let task = document.getElementById("task_input_field").value;
  let list = document.getElementById("to-do_list");
  list.innerHTML += `<li>${task}<button type="button"onclick="deleteTask(event)">X</button></li>`
}

function deleteTask(event) {
  const target = event.currentTarget.closest("li");
  document.getElementById("to-do_list").removeChild(target)
}
<input type="text" id="task_input_field">
<button onclick="addTaskToTheList()">Add</button>
<ul id="to-do_list"></ul>
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