itemElement.onclick=function(){
//remove element from view
this.parentNode.removeChild(this);
//find the element that was clicked on in the array
//which should be itemElement(aka this)????
var index=itemArray.indexOf(this);
//remove it from the array
itemArray.splice(index,1);
//console.log to check
console.log(itemArray);
}
That is my code I am currently using to delete items from a list. I want the user to be able to click on the item in their list they want to delete, delete it from the view and then delete it from an array of items. Deleting the element from the view is working fine, but for some reason its only deleting the last element added to the array, not the actual element that was clicked on. So if the user makes a list that has Bob,Tom,Rob and then clicks on Tom, Tom is no longer displayed in the list but Rob will be deleted from the array.
Here is that whole block of code
const addButton =<HTMLButtonElement>document.querySelector("#addButton");
const saveButton = document.querySelector("#saveButton");
const itemsSection = document.querySelector("#itemsSection");
const itemArray: Array<string> = [];
let itemElement;
let newItem: string;
let itemText: string;
//add new item to shopping list
addButton.onclick=function addItem(){
//add each item to the list
itemElement = document.createElement("li");
newItem = (<HTMLInputElement>document.querySelector("#newItem")).value;
itemText = document.createTextNode(newItem);
itemElement.appendChild(itemText);
itemsSection.appendChild(itemElement);
document.querySelector("#newItem").value="";
//push each item to our array to store in local storage
itemArray.push(newItem);
console.log(itemArray);
itemElement.onclick=function deleteItem(){
var index=itemArray.indexOf(this);
this.parentNode.removeChild(this);
itemArray.splice(index,1);
console.log(itemArray);
}
}
As you can see im using typescript
var index=itemArray.indexOf(this);this will return -1, which will eventually remove last element from the Array