Home > Enterprise >  How to delete an item from an unordered list?
How to delete an item from an unordered list?

Time:04-17

function render(Leads){
let listItems = ""
for(i = 0; i < Leads.length; i  ){
    listItems  = `
        <li>
            <a href='${Leads[i]}' target='_blank'> 
                ${Leads[i]} 
            </a>
            <button id="delete">❌</button>
        </li>`
}
ulEl.innerHTML = listItems}

I am trying to make a leads tracker app and I have written this code. I want to make the delete button functional, but I have no idea how I can delete a specific item from an unordered list.

CodePudding user response:

  • in the for loop make id=item${i}
  • Add another function that take id as a prameter Ex: deleteItem(id)
  • in the deleteItem function you can filter and delete what you want

CodePudding user response:

the first problem is there are multiple button elements with same id, id should be unique.

Here you can add an eventListenar to the ulEl element and on clicking the button we should remove the element

function render(Leads){
let listItems = ""
for(i = 0; i < Leads.length; i  ){
    listItems  = `
        <li>
            <a href='${Leads[i]}' target='_blank'> 
                ${Leads[i]} 
            </a>
            <button id="delete${i}">❌</button>
        </li>`
}
ulEl.innerHTML = listItems;
}

ulEl.addEventListener("click", function (event) {
  if(event.target.id?.includes("delete")) {
    let id =  event.target.id.replace("delete", "") // to get the last character 
    leads.splice(id, 1); // remove the element(please use the corresponding 
                         //   variable, here I am using leads)
    list.innerHTML = ""; // clearing current list
    list.innerHTML = leads.reduce((acc, curr, idx) => {
      acc  = `
      <li>
          <a href='${curr}' target='_blank'> 
              ${curr} 
          </a>
          <button id="delete${idx}">❌</button>
      </li>`;

      return acc;
    }, "");
  }
});

Hope this helps thank you

  • Related