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
Download it – dynamically-add-remove-item-from-list-javascript
References
- document.createElement documentation
- document.createTextNode documentation
- node.appendChild documentation
- node.removeChild documentation
Add Button is working fine however RemoveItem is not working any solution???
The
RemoveItem
works by removing an item by its value, have you tried the jsfiddle?How could I get a specific item from a list using like a number to specify a position. Like if the list has 20 items in it how do I get the 10th item?
Awesome! Code worked well – thanks!
Now enhancing for creating elements from array instead of manual entry.
Cheers!