In the following article, we dynamically add and remove list items using JavaScript. We are using JavaScript to add and/or remove list items dynamically which means that if we run our webpage it will show the option of adding and removing items using buttons.
Approach: In the webpage, one input text box is given for the user entry to add a list item. Two buttons are given to add a list item and also remove a list item. The list items are added or removed using JavaScript functions addItem() and removeItem(). The list items are created using document.createElement() method and to create a text node, document.createTextNode() method is used and then this node is appended using appendChild() method. The list item is deleted using the removeChild() method.
The in-built functions used are listed below.
- Create new elements: We can create new elements using the document.createElement() function. It will create elements dynamically.
- Append element: We can append elements using the function appendchild().
- Create text node: We can create a text node using the document.createTextNode() element. HTML consists of both an element node and a text node. So createTextNode() method creates a text node with the specified text.
- Remove existing element: We can remove a child from the created list by using removechild() function.
Example: The following code demonstrates the addition and deletion of list items using JavaScript functions.
HTML
<!DOCTYPE html> < html lang = "en" > < head > < style > #candidate { border-radius: 20%; border-color: aquamarine; box-sizing: border-box; } .buttonClass { border-radius: 20%; border-color: aqua; border-style: inherit; } button:hover { background-color: green; } </ style > </ head > < body > < ul id = "list" ></ ul > < input type = "text" id = "candidate" /> < button onclick = "addItem()" class = "buttonClass" > Add item</ button > < button onclick = "removeItem()" class = "buttonClass" > Remove item</ button > < script > function addItem() { var a = document.getElementById("list"); var candidate = document.getElementById("candidate"); var li = document.createElement("li"); li.setAttribute('id', candidate.value); li.appendChild(document.createTextNode(candidate.value)); a.appendChild(li); } // Creating a function to remove item from list function removeItem() { // Declaring a variable to get select element var a = document.getElementById("list"); var candidate = document.getElementById("candidate"); var item = document.getElementById(candidate.value); a.removeChild(item); } </ script > </ body > </ html > |
Output: Now, click on add item to add any item to the list. Click on remove item to delete any item from the list.