I want to put a DELETE button next to each new appended <li>
element that should delete the item, but I can't figure out how.
let addBtn = document.getElementById("add-btn"); addBtn.addEventListener("click", function() { var item = document.getElementById("item").value; var text = document.createTextNode(item); var li = document.createElement('li'); li.appendChild(text); document.getElementById('todo-list').appendChild(li); })
<.DOCTYPE html> <html lang="en"> <head> <link rel="stylesheet" href="style,css"> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width. initial-scale=1.0"> <title>Document</title> </head> <body> <div class="container"> <div class="add-todo"> <input type="text" id="item"> <button type="submit" id="add-btn">ADD</button> </div> <div class="added-lists"> <ul id="todo-list"></ul> </div> </div> </body> <script src="/script.js"></script> </html>
Create a new button
element and append it to the li
. Add a click event listener on the button that calls a function, and inside the function delete the buttons' parent element.
let addBtn = document.getElementById("add-btn"); addBtn.addEventListener("click", function() { var item = document.getElementById("item").value; var text = document.createTextNode(item); var li = document.createElement('li'); var btn = document.createElement("button"); btn.textContent = "x"; btn.style.marginLeft = "10px"; li.appendChild(text); li.appendChild(btn); document.getElementById('todo-list').appendChild(li); btn.addEventListener('click', function() { this.parentElement.remove(); }) })
<.DOCTYPE html> <html lang="en"> <head> <link rel="stylesheet" href="style,css"> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width. initial-scale=1.0"> <title>Document</title> </head> <body> <div class="container"> <div class="add-todo"> <input type="text" id="item"> <button type="submit" id="add-btn">ADD</button> </div> <div class="added-lists"> <ul id="todo-list"></ul> </div> </div> </body> <script src="/script.js"></script> </html>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.