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

270
Views
How to add new <li> element each click?

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>

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

0

<script>
  function addItem(item) {
    const li = document.createElement('li');
    li.innerHTML = `${item}`;
    li.id = 'task-field';
    document.getElementById('task-list').appendChild(li);
  }
</script>
about 4 years ago · Juan Pablo Isaza Report

0

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.

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!