I need help with deleting an object from the array.
The names(array.name) from the objects are displayed in the DOM and I want to delete them using the erase X button .
In this code I can only delete one element and then stops working with no console error. Does anyone have an idea where I am wrong and why I can't call the create() function every time I click on an erase button.
Look at console.log... it shows the good position and name of the element to be deleted, but everything stops when I call create() function, try uncomment create().
const array = [ {name: 'John'}, {name: 'David'}, {name: 'Peter'}, {name: 'Michael'} ];
const create = () => {
const app = document.querySelector('.app');
app.innerHTML = '';
for(let i = 0; i < array.length; i++) {
app.innerHTML += `<div class="item"><span class="erase">☓</span>${array[i].name}</div>`;
}
}
create();
const erase = document.querySelectorAll('.erase');
erase.forEach(item => {
item.onclick = () => {
const itemText = item.parentElement.textContent.substr(1);
const itemPos = array.findIndex(item => item.name == itemText);
console.log(itemText + ' ' + itemPos);
console.log(array);
array.splice(itemPos, 1);
//create()
}
});
.erase {
color: red;
margin-right: 20px;
cursor: pointer;
}
.item {
margin-bottom: 10px;
}
<div class="app"></div>
Or as fiddle: https://jsfiddle.net/05cwy9d2/3/
Its because when you create new elements in the dom the listeners of old elements are being removed together with the old elements. Just move the event listener registration into create method.
const array = [
{name: 'John'},
{name: 'David'},
{name: 'Peter'},
{name: 'Michael'}
];
const create = () => {
const app = document.querySelector('.app');
app.innerHTML = '';
for(let i=0;i<array.length;i++){
app.innerHTML +=
`<div class="item"><span class="erase">☓</span>${array[i].name}</div>`;
}
const erase = document.querySelectorAll('.erase');
erase.forEach(item => {
item.onclick = () => {
const itemText = item.parentElement.textContent.substr(1);
const itemPos = array.findIndex(item => item.name == itemText);
console.log(itemText + ' ' + itemPos);
console.log(array);
array.splice(itemPos, 1);
create();
}
});
}
create();
.erase{
color: red;
margin-right: 20px;
cursor: pointer;
}
.item{
margin-bottom: 10px;
}
<div class="app"></div>
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments