I made a to-do list, when adding an item, it can be edited and deleted. How can rewrite the function createEditAndDeleteElement so that it is less cumbersome or how to break it up into several parts. When I tried to break it, it displayed an error with li. Please, help
const input = document.getElementById('list');
const btnAdd = document.querySelector('.btn-add');
const toDoList = document.querySelector('.todo-list');
btnAdd.addEventListener('click', () => {
if(input.value === '') {
return
}
createEditAndDeleteElement(input.value)
input.value ='';
});
function createEditAndDeleteElement(value) {
const li = document.createElement('li');
const btnDelete = document.createElement('button');
const btnEdit = document.createElement('button');
li.className = 'todo-list-item';
li.textContent = value;
btnDelete.className = 'btn-delete';
btnDelete.textContent = 'delete';
btnEdit.className = 'btn-edit';
btnEdit.textContent = 'edit';
li.appendChild(btnDelete);
li.appendChild(btnEdit);
btnDelete.addEventListener('click', () => {
toDoList.removeChild(li);
});
btnEdit.addEventListener('click', () => {
const editInput = document.createElement('input');
const saveEdit= document.createElement('button');
saveEdit.className = 'btn-save';
saveEdit.textContent = 'Save';
toDoList.removeChild(li);
toDoList.appendChild(editInput);
toDoList.appendChild(saveEdit);
editInput.value = li.textContent;
saveEdit.addEventListener('click', () => {
toDoList.removeChild(editInput);
toDoList.removeChild(saveEdit);
createEditAndDeleteElement(editInput.value)
})
});
toDoList.appendChild(li);
};
I would use a templates: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/template
let template = document.getElementById('newElement'); let templateContent = template.content; document.getElementById('addNew').onclick = createElement function createElement() { document.body.appendChild(templateContent); } function handleActions(action){ console.log(action) }
<body> <button id="addNew">Test</button> <template id="newElement"> <button onclick="handleActions('Action 1')">Action1</button> <button onclick="handleActions('Action 2')">Action2</button> </template> </body>
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.