0

I'm, struggling a little bit trying to understand the way .append and .html works. I have this code which generates a new <li> element when clicking a button:

The way that it's written below works fine. The thing is that if instead of .html() I use .append() it add a new <li> plus all the others, not just ONE <li>

Can someone explain to me why does it happen? Thanks in advance :)

const showTask = () =>{
    let itemHtml = "";
    toDoList.forEach((item, index)=>{
        
        itemHtml += 
            `<li class="item ${item.isCompleted == true ? " item-is-done" : ""}" id="${index}"><input type="checkbox" class="checkbox"><span>${item.task}</span>               
                <button type="button" class="remove" onClick="deleteTask(${index})"><i class="bi bi-trash" id="remove-btn"></i></button>
            </li>`;
    });

    $(".list").html(itemHtml);
};
Phil
  • 157,677
  • 23
  • 242
  • 245

2 Answers2

0

.html() overwrites everything of your .list.

.append() adds the element at the end of your .list.

Jakob
  • 1,858
  • 2
  • 15
  • 26
0

html function remove previous data and write new one you should use append to keep previews

  • and add new one