Reputation: 11
I'm not quite sure how to phrase my main question in the title but I'll try my best to explain it down here. I'm creating a javascript app that takes user input and then adds it as a list item into a list. I want each list item to have a button that will delete the corresponding list item when pressed. Here is my code:
function addToList(){
removeBtn = document.createElement('button');
listItem = document.createElement('li');
listItem.textContent = row[0]+ ' $' + row[1]+ ' ' + row[2]+' ';
removeBtn.addEventListener('click', removeLi);
listItem.appendChild(removeBtn);
list.append(listItem);
}
I've tried a couple things but I just dont know what to put in my removeLI function that will delete the parent <li>
of the button that got clicked. Any help would be much appreciated
Upvotes: 0
Views: 31
Reputation: 207501
Use the event target and reference the li element with closest
function removeLi(event) {
event.target.closest('li').remove()
}
var list = document.querySelector("#list")
function addToList(text){
var removeBtn = document.createElement('button');
var listItem = document.createElement('li');
listItem.textContent = text
removeBtn.addEventListener('click', removeLi);
listItem.appendChild(removeBtn);
list.append(listItem);
}
addToList(1)
addToList(2)
addToList(3)
<ul id="list"></ul>
Upvotes: 1