Javascript Dynamic List Creation

So you want to have your javascript dynamically add structure to your page without reloading. Yes, you can do this, and it all comes down to the document.createElement function, which works in at least Firefox 1.0.3, IE 6, and Konqueror.

How to do this? It’s actually a fairly simple javascript function that does this:


function listAdd(input)
{
// Input mode
var list = document.getElementById('thelist');
var element = document.createElement("LI");
element.innerHTML=input;
list.appendChild(element);
}

First off, we get an element named ‘thelist’ — this is the OL or UL tag enclosing your list. Then, we create a new element. In this case, it’s a “LI” element. Next, we use the innerHTML property to set what goes inside the LI and /LI tags — in other words, innerHTML is what’s inside the tags. Finally, we use the appendChild function to add the element we created to the list.

The end result can be seen and tested here.

Overall, it’s a fairly simple but highly effective little technique that you can add to your bag of tricks.

Published by

matt

I'm a software engineer in New Orleans interested in making things, growing things, big fast computers, media convergence, and pugs.

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=""> <s> <strike> <strong>