A web developer's blog. PHP, MySQL, CakePHP, Zend Framework, Wordpress, Code Igniter, Django, Python, CSS, Javascript, jQuery, Knockout.js, and other web development topics.

Adding and Removing a List Item to a List Using Javascript dynamically

There are a couple of ways to do this but I find this one the simplest.

First, you create your HTML Code such as below:

<strong>Below is a list item:</strong>
<a href="#" onclick="addListItem('the_list'); return false;">add item</a>
<input id="list_counter" value="2" type="hidden" />
<ol id="the_list">
<li id="listItem_0">This is a list item.</li>
<li id="listItem_1">This is another list item.</li>
<li id="listItem_2">Yet another list item.</li>
</ol>

The ID for the UL tag and LI tags will be used by the Javascript code below:

function addListItem(listId) {
     var listOfItems = document.getElementById(listId); //get the list ID
     var listCounter = document.getElementById('listCounter'); //get the hidden list counter
     var listCounter_value = listCounter.value; //get the value of the hidden list counter
     var new_li = listOfItems.createElement('li'); //create a new LI element
     new_li.setAttribute('id','listItem_'+listCounter_value); //make the ID for the new element
     new_li.innerHTML = '<em>This is an italicized list item.</em><a href="#" onclick="removeItem(listItem_'+listCounter_value+')">remove this item</a>'; //the stuff that is inside the LI
     listOfItems.appendChild(new_li); //add the new LI
     listCounter.value = listCounter_value++; //update the value of the list counter
}
 
function removeItem(listItem) {
     var listOfItems = document.getElementById('the_list'); //get the list
     var targetListItem = document.getElementById(listItem); //the specific list item, that's why we placed created an attribute for it
     listOfItems.removeChild(targetListItem); //this removes the list item
}
This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>