Search code examples
javascriptarraysfor-loopdomappendchild

Adding a delete button to a list


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);
}


Solution

  • 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);
    }