Dynamically Add/Remove Items From List JavaScript

This tutorial shows how to dynamically add and/or remove items from a list using JavaScript.

  • create new element: We can dynamically create new elements using the document.createElement function.
  • append element: We can append elements using the appendChild function.
  • create text node: We can create a text node using the document.createTextNode element.
  • remove existing element: We can remove a child from the list, using the removeChild function.
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Dynamically add/remove items from list - JavaScript</title>
</head>
<body>

    <ul id="dynamic-list"></ul>

    <input type="text" id="candidate"/>
    <button onclick="addItem()">add item</button>
    <button onclick="removeItem()">remove item</button>

    <script src="script.js"></script>
</body>
</html>

The script.js is located in the same directory as the html page.

function addItem(){
    var ul = document.getElementById("dynamic-list");
    var candidate = document.getElementById("candidate");
    var li = document.createElement("li");
    li.setAttribute('id',candidate.value);
    li.appendChild(document.createTextNode(candidate.value));
    ul.appendChild(li);
}

function removeItem(){
    var ul = document.getElementById("dynamic-list");
    var candidate = document.getElementById("candidate");
    var item = document.getElementById(candidate.value);
    ul.removeChild(item);
}

Demo



Download

References

You may also like...