0

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

1
  • I strongly suggest putting const, let or var in front of your variable declarations. Using global variables like this is going to lead to problems Commented May 1, 2020 at 0:11

1 Answer 1

1

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>

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for helping me out, just added it to my program and it works great. Since that code doesn't explicitly pass anything into removeLI, does the "event" get passed into it automatically?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.