We can use the appendChild method and JavaScript to add a node to the end of another node.
document.getElementById("list").appendChild(node);
In the code above, appendChild() takes a node and will add it to the end of a list of nodes that we have.
We can create a new node using the Document createElement() method. Let’s take a look at a quick example below.
Let’s say we have the following HTML:
- One
- Two
If we wanted to add another li element to the list above, we can create a new li element and then add it to the list using the appendChild() method.
var newListItem = document.createElement('li');
newListItem.textContent = "Three";
document.getElementById("list").appendChild(newListItem);
This will add the list item “Three” to the end of this list. Let’s take a look at an interactive example below.
Using the appendChild Method and JavaScript to Add Items to a List
In this example, we will have a simple list as we had above. We will then have an input field below the last that will allow the user to add as many list items to the list as they like.
Here is the HTML setup:
- A list item
- Add any text you like
Add Item
In this JavaScript code, we will get the user input using the value property and an onclick event. We will then create a new list item using document.createElement method, and then finally we will add the new item to the end of the list using the appendChild() method.
Here is the JavaScript code:
function updateList(){
var userInput = document.getElementById("new-item").value;
var newListItem = document.createElement('li');
newListItem.textContent = userInput;
document.getElementById("theList").appendChild(newListItem);
};
The final code and output for this example of adding items to a list using appendChild() and JavaScript is below:
Code Output:
- A list item
- Add any text you like
Full Code:
- A list item
- Add any text you like
Add Item
<script>
function updateList(){
var userInput = document.getElementById("new-item").value;
var newListItem = document.createElement('li');
newListItem.textContent = userInput;
document.getElementById("theList").appendChild(newListItem);
};
</script>
Hopefully this article has been useful to help you understand how to add items to a list using the appendChild method and JavaScript.