Search code examples
javascripthtmljsdompure-js

Delete item of html table coming from input in JS DOM


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


Solution

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