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.

Change font-size using JavaScript Get Font Size of any Tag using JavaScript Change Position of HTML Element using JavaScript How to Change Image on Hover with JavaScript How to Disable Button by Class Name in JavaScript How To Change Image Size with JavaScript How to change Image opacity with JavaScript How to Change image src on click with JavaScript How to get the lang attribute value in JavaScript How to Get attribute Value using JavaScript How To Check if Attribute Exists or not with JavaScript How To Count number of links on Page with JavaScript How To Scroll Page to Bottom using 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