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

Time:10-16

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?

CodePudding user response:

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>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

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>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

const c = document.createElement('li');
c.innerText = 'item 3';
document.getElementById('my-list').appendChild(c);
<ul id="my-list">
   <li>item 1</li>
   <li>item 2</li>
</ul>
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

I think you need to be more specific with what your code is actually doing, but I can say that someListItemICreated should not be a string, if that's what you're passing. Here's an example I made that's similar to what you're referring to that runs fine.

<ul id="my-list">
  <li>Item 1</li>
  <li>Item 2</li>
</ul>
let someListItemICreated = document.createElement("li");
someListItemICreated.appendChild(document.createTextNode("item 3"));

document.getElementById("my-list").appendChild(someListItemICreated)
  • Related