0

Trying to add a delete button to a to do list using javascript DOM manipulation. The problem is when I appendChild() in my for loop. It only appends the button I created to the last list item.

<div id="list">
    <ul>
        <li class="bold red" random="23">Notebook</li>
        <li>Jello</li> 
        <li>Spinach</li>
        <li>Rice</li>
        <li>Birthday Cake</li>
        <li>Candles</li>
    </ul>
</div>

var item = document.querySelectorAll("li");
var button = document.createElement("button");
var buttonText = document.createTextNode("delete");
button.appendChild(buttonText);
for (var i = 0; i < item.length; i++) {
    item[i].appendChild(button);
}

2
  • Can't you just directly add an inline button in your HTML? Commented Apr 22, 2020 at 21:50
  • @AdilRaza yeah I could, but the list is interactive and not static. So using DOM manipulation to eventually create buttons automatically as more items are entered into the list on the browser. Thank you for the input though! Commented Apr 23, 2020 at 1:15

1 Answer 1

1

Only one button exists so you are moving it from li to li and it ends up in the last one. You can create a new button each iteration so they all get a delete button.

var item = document.querySelectorAll("li");

for (var i = 0; i < item.length; i++) {
    var button = document.createElement("button");
    var buttonText = document.createTextNode("delete");
    button.appendChild(buttonText);
    item[i].appendChild(button);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.