Is there any way / method in javascript to add a node child to dynamically display the element?
If I have an unordered list like
<ul id="list"> <li>Helo World-1</li> <li>Helo World-2</li> <li>Helo World-3</li> </ul> I want to add a subscription element to it dynamically. Is there any method in javascript for this. How could I do that. edit I need an element on the next level, i.e. The optional Helo World list that I mentioned in the OP too, is something like this. Another problem is that I need the elements to be a constant part of my code.
<ul id="list"> <li>Helo World-1</li> <li>Helo World-2</li> <li>Helo World-3</li> <ul> <li>One</li> <li>Two</li> </ul> </ul> Using pure DOM methods:
var ul = document.getElementById("list"); var li = document.createElement("li"); li.appendChild(document.createTextNode("Your list item text")); To add a list item to the end of the list:
ul.appendChild(li); Insert a list item between existing list items (note that in this example you need to specify an existing list item):
ul.insertBefore(li, document.getElementById("list_item_id")); Update
If you want to add a nested list, you need to add it to the list item, and not directly inside the list so that it is valid:
var lis = ul.getElementsByTagName("li"); var lastLi = lis[lis.length - 1]; var nestedUl = document.createElement("ul"); var nestedLi = nestedUl.appendChild(document.createElement("li")); nestedLi.appendChild(document.createTextNode("One")); lastLi.appendChild(nestedUl); I created a sample in jsfiddle
var el = document.getElementById("list"); var li = document.createElement("li"); li.innerHTML = "item"; el.appendChild(li); You can view the w3schools html dom reference to see how we can manipulate html elements with javascript.
But I think that a cleaner way would be to use a third-party library, for example jQuery , which will greatly simplify the management of the house.
ex: If using jQuery, it will be as simple as
$("<li>...</li>").appendTo("#list") EDIT: Based on your editing, you can try this,
var ul = document.getElementById("list"); ul.children[2].innerHTML = "<ul><li>sub 1</li><li>sub 2</li><li>sub 3</li></ul>"; This will get the third <li> of <ul> and add subscriptions to it
$('<li>...</li>').appendTo($('#list')); /* in jquery */ otherwise direct js
var mylist = document.getElementById('list'); mylist.appendChild(document.createElement('li')); Note: if you need to also set the text
var mylist = document.getElementById('list'); var newli = document.createElement('li'); newli.innerHTML('Helo World ' + mylist.getElementsByTagName('li').length + 1); mylist.appendChild(newli); AFAIK, there is no equivalent HTML DOM object for a list. In any case, you can use innerHTML:
var list = document.getElementById("list"); var item = "<li>New Item</li>"; list.innerHTML += item;