Add list item to ul JavaScript

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.

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.

How To Detect Shift Key Press with JavaScript Change Text Color On Hover with JavaScript Hide and Show div using JavaScript Get Button text with JavaScript Get textarea value with JavaScript Get table row Height with JavaScript Auto Increase width of input field with JavaScript Set Textarea maxLength with JavaScript Set Textarea Value with JavaScript JavaScript Count list items JavaScript set input field value Count Button Clicks with JavaScript Scroll Page to the Top on Click with JavaScript Change id of Element with JavaScript JavaScript Change li Text Color JavaScript Change li Text JavaScript Remove id from Element Check If id Exists in JavaScript How To Delete Table Row by id in JavaScript Update Textarea value in JavaScript Change Variable Value in JavaScript Uncheck Radio Button Dynamically JavaScript Check Radio Button Dynamically JavaScript JavaScript Check if Radio Button is Checked or Not Change h1 Tag Text with JavaScript