In this tutorial we will see how to append list item to the ul tag using JavaScript. HTML DOM createElement() method, createTextNode() method and appendChild() method can be used to add li tag to the ul tag.
Table of Contents
HTML DOM createElement() method
The HTML DOM createElement() method creates an element node or HTML tag.
In this example createElement() method will create a list item or li tag to add it into the ul tag.
HTML DOM createTextNode() method
The HTML DOM createTextNode() method creates a text node.
In this example createTextNode() method will create a text node for the li tag. This text node is basically a text that would be written inside the li tag.
HTML DOM appendChild() method
The HTML DOM appendChild() method appends or adds the HTML element into another element as it's last child.
In this example appendChild() method will add the list item to the ul tag as the last child.
HTML Code
HTML Code is given below, This code contains a ul tag with three list items.
A button tag is used with onclick event to execute a JavaScript function.
<ul id="lang">
<li>HTML</li>
<li>CSS</li>
<li>JavaScript</li>
</ul>
<button onclick="appendLi()">Add Li</button>
JavaScript Code
JavaScript Code is given below, in this code first we have created a list item using createElement() method, then text node is created for this li tag using createTextNode() method and finally the text node is added to list item which is then added to the ul tag.
getElementById() method is used to target or select the ul tag.
<script>
function appendLi()
{
var ul = document.getElementById("lang");
var li = document.createElement("li");
var text = document.createTextNode("PHP");
li.appendChild(text);
ul.appendChild(li);
}
</script>
Demo
Video Tutorial
Watch video tutorial on how to Add li tag to ul tag with JavaScript.