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();
}
}
I see two issues here:
'.delete'
, not all elementsaddItem
won't have the listener attached to themYou can fix both by using event delegation: assign the listener on a common parent:
document.querySelector("table").addEventListener("click", deleteItem)