Delete item of html table coming from input in JS DOM

204 Views Asked by At

I have problem with deleting operation in html table in JS. I trying to delete item of table which coming from input.It is nothing happen.

const name = document.querySelector(".name");
const surname = document.querySelector(".surname");
const age = document.querySelector(".age");
const addBtn = document.querySelector(".addBtn");
const deleteBtn = document.querySelector(".delete");
const tbody = document.querySelector(".tbl");

addBtn.addEventListener("click",addItem);
deleteBtn.addEventListener("click",deleteItem);

function addItem(e){
    var html = `<tr>
                    <td>${name.value}</td>
                    <td>${surname.value}</td>
                    <td>${age.value}</td>
                    <td class="delete">DELETE</td>
                </tr>`;
    if(name.value === '' || surname.value === '' || age.value === ''){
        alert("Warning!!!");
    }else{
        tbody.innerHTML += html;
    }
    e.preventDefault();
}
function deleteItem(e) {   
        if(e.target.className = 'delete'){
           e.target.parentElement.remove();
        } 
}

2

There are 2 best solutions below

1
On BEST ANSWER

I see two issues here:

  1. The event listener is assigned to the first element that matches '.delete', not all elements
  2. Buttons that will be created via addItem won't have the listener attached to them

You can fix both by using event delegation: assign the listener on a common parent:

document.querySelector("table").addEventListener("click", deleteItem)
0
On

Your table rows are added dynamically, you bind the event listener before the content is loaded into the dom(your row is added only when you call the addItem method). One way you can fix is, add event listener after appending content to the table every time.

Something like this

if(name.value === '' || surname.value === '' || age.value === ''){
     alert("Warning!!!");
}else{
     tbody.innerHTML += html;
     document.querySelector(".delete").addEventListener("click",deleteItem);
}