Home > Software design >  How to add new <li> element each click?
How to add new <li> element each click?

Time:02-15

First attempt at any sort of Javascript so be gentle aha

Have managed to have the page add the new list item to the inner html of an unordered list, but each time after that it just replaces the initial.

I feel like I'm missing something really basic here?

Any advice would be greatly appreciated.

    <script>
        function addItem() {
            var item = document.getElementById("task-field").value;
            document.getElementById("task-list").innerHTML = "<li> "   item   " </li>";
        }
    </script>

CodePudding user response:

Use

document.getElementById("task-list").innerHTML  = "<li> "   item   " </li>";

instead of

document.getElementById("task-list").innerHTML = "<li> "   item   " </li>";

The = operator will use the current value of innerHTML and append your new content in this case. This as suggested by @Hassam Imam.

Another way of doing it is using appendChild() creating the new <li> item through JS. Like this:

function addItem() {
    let item = document.getElementById("task-field").value;
    let parent = document.getElementById("task-list");
    
    // Create new node.
    let li_item = document.createElement("li");
    li_item.innerHTML = item;
    
    // Append child.
    parent.appendChild(li_item);
}

But this last method is probably too lengthy. The = solution seems good. Just another way of doing it.

CodePudding user response:

<script>
  function addItem(item) {
    const li = document.createElement('li');
    li.innerHTML = `${item}`;
    li.id = 'task-field';
    document.getElementById('task-list').appendChild(li);
  }
</script>
  • Related