Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

313
Views
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?

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

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>

about 4 years ago · Juan Pablo Isaza Report

0

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)
about 4 years ago · Juan Pablo Isaza Report

0

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>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!