JavaScript Code


How to add list item to list element in document using JavaScript?


Tutorials using JS

Add item to list element

Given a list element in the HTML document, add an item to this list element as child, using JavaScript

Solution

To add a list-item element as child to the list element in the document, create the list-item using document.createElement() method, and add this list-item to the list element using Element.appendChild() method.

//create list-item
const listItem = document.createElement("li");
const textNode = document.createTextNode("Water");
listItem.appendChild(textNode);

//append list-item to list
document.getElementById("myList").appendChild(listItem);

Program

In the following HTML code, we have a list element #myList. When user clicks on the button Click Me, we will add a list-item 'cherry' to the list element.

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Tutorial</h1>
<h2>Add list-item to list element</h2>
<button id="myBtn">Click me</button><br>
<ul id="myList">
    <li>apple</li>
    <li>banana</li>
</ul>

<script>
//set onclick listener for #myBtn
document.getElementById("myBtn").addEventListener("click", function() {
    //create list-item
    const listItem = document.createElement("li");
    const textNode = document.createTextNode("cherry");
    listItem.appendChild(textNode);

    //append list-item to list element
    document.getElementById("myList").appendChild(listItem);
});
</script>

</body>
</html>

Copyright @2022