Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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>

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading