0

I am unable to add a delete button to a list item in my code, pls I need assistance. Below is my code

function addDeleteBtn() {
  const ul = document.querySelector("ul");
  let li = document.querySelectorAll("li");
  let btn = document.createElement("button");
  const text = document.createTextNode("delete");
  btn.appendChild(text);
  for (const item of li) {
    li.append(btn);
  }

  ul.appendChild(li);
}
addDeleteBtn();
williams
  • 13
  • 4
  • Can you show the corresponding HTML? – lurker Jan 09 '22 at 14:01
  • `li` is a `NodeList`. `NodeList` objects don't have an `append` function. You may have meant `item.append(btn);` instead of `li.append(btn);` but note that your button will end up appended to only the **last** item in the list, since you're reusing the same button each time. When you append an element that's already elsewhere in the document to a new parent, it gets *moved* from its old parent to its new one. If you want to create new buttons every time, you have to do so within the loop. – T.J. Crowder Jan 09 '22 at 14:02
  • The logic is a little confusing. Exactly which list item do you want the delete button appended to? The code seems to be trying to append it to all of your list items. But it has an error in that regard since your loop has `li.append` instead of `item.append`. `li` isn't a very good name for that variable since, as TJ points out, it represents a node list, not just one item. Proper variable naming can avoid confusion in your code, for you and for anyone else reading it. – lurker Jan 09 '22 at 14:08

0 Answers0