Search code examples
javascripthtmlappendchild

How do I add child <li> elements to <ul> without removing current children


How do I iteratively add children elements to a (for example) a .

<ul id="my-list">
   <li>item 1</li>
   <li>item 2</li>
</ul>

If I have a JS script that runs something like this several times:

document.getElementById('my-list').appendChild('someListItemICreated')

the current 2 list items are removed. How do I add new li items to the ul without losing the current list itmes?


Solution

  • You need to provide an element as the argument for appendChild and not a string. Like this:

    const li = document.createElement("li");
    li.innerText = "Item 3";
    document.getElementById("my-list").appendChild(li);
    <ul id="my-list">
      <li>Item 1</li>
      <li>Item 2</li>
    </ul>

    A much easier and a cleaner approach that I prefer in most of cases is:

    document.getElementById("my-list").innerHTML += "<li>Item 3</li>";
    <ul id="my-list">
      <li>Item 1</li>
      <li>Item 2</li>
    </ul>