Welcome to WebmasterWorld Guest from

Forum Moderators: open

Message Too Old, No Replies

add elements dynamically to an unordered list

8:12 pm on Mar 27, 2012 (gmt 0)

Junior Member

5+ Year Member

joined:May 18, 2011
votes: 0

HI there, I am looking at some exercises found here and there on the net, and I am attempting to resolve one which basically asks to populate a unordered list with items. I am having quite a few problems, although I'd say that's probably an easy thing to do. ANyway, code's here:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<link rel = "stylesheet" type = "text/css" href = "style.css">
<script type = "text/javascript" src = "script.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>

<body onload = "getCities()">
<div id = "cities">
<ul id = "cities_list">






height: 400px;






var city_arr = new Array("London", "Madrid", "Leeds", "Barcelona");

var index;

function getCities(){

for (index = 0; index < city_arr.length; index++)





Now, the idea is that I have already an unordered list on my html. The list is hidden with css and the script should add the elements of the array in the list, but it's not happening
Any idea as to why? and perhaps suggestion as to how to proceed please?
11:36 pm on Mar 27, 2012 (gmt 0)

Senior Member

WebmasterWorld Senior Member 10+ Year Member

joined:Nov 3, 2005
votes: 0

var index;
would be better declared within function getCities as it is only used inside this function.

You are doing this on each li, it is the ul that is hidden, move to after the for loop.

This will fail as the li does not a id on it, instead try
and remove empty li's from html.
10:22 pm on Mar 28, 2012 (gmt 0)

Junior Member

5+ Year Member

joined:May 18, 2011
votes: 0

yes, thanks daveVk that works a treat. I didn't know that $("li#cities_list").html("city_arr[index]").show('fast'); the html method within the loop doesn't assign 4 bullet point to the list but at every run it clears the previous item and adds another one, therefore leaving me with only 1 bullet point. It took me a while to understand that, I simply thought that there was an error in my code.

Join The Conversation

Moderators and Top Contributors

Hot Threads This Week

Featured Threads

Free SEO Tools

Hire Expert Members