I've written a Todo task app, using JSON-Server, to manage the REST routing.
I've uploaded my code here: https://codesandbox.io/s/json-server-i5hv5
Problem I'm having, is that when I click on a todo task, I want to delete only that DIV by {id}
, from the database.
However, the delete function only works, if you click on the last div added. And even then, it deletes all {id}'s in the DB and divs on the page, rather than the single div, I've clicked on.
Struggling to make this work.
I want to only delete the div I click on. And I only want that div to be removed in the DB, by it's allocated id={id}
.
This is the click function in question:
document.getElementById('id').addEventListener('click', function(event)
{
event.preventDefault();
console.log('clicked');
var divs = document.querySelectorAll('div');
for (var i = 0; i < divs.length; i++) {
var id = divs[i].getAttribute('id');
divs[i].parentElement.removeChild(divs[i]);
fetchService.deleteTodoTask(id);
}
});
Any approaches/tips, would be grateful!
I got this working, by changing the way I'm accessing the DOM element on click. And the below code seems to work well.
I'm them passing the grabbed ID on click, into fetchService.deleteTodoTask(id)
.
Which is where the delete REST route is being handled:
const list = document.querySelector('.js-todo-list');
list.addEventListener('click', event => {
if (event.target.classList.contains('js-delete-todo')) {
const itemKey = event.target.parentElement.dataset.key;
const id = itemKey;
var elem = document.getElementById(id);
elem.parentNode.removeChild(elem);
fetchService.deleteTodoTask(id);
}
});
function deleteTodoTask(id) {
const options = {
method: 'DELETE'
};
return fetch(`${url}/${id}`, options);
}