homepage Welcome to WebmasterWorld Guest from
register, free tools, login, search, pro membership, help, library, announcements, recent posts, open posts,
Become a Pro Member

Home / Forums Index / Code, Content, and Presentation / JavaScript and AJAX
Forum Library, Charter, Moderator: open

JavaScript and AJAX Forum

add elements dynamically to an unordered list

Msg#: 4434095 posted 8:12 pm on Mar 27, 2012 (gmt 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?



WebmasterWorld Senior Member 5+ Year Member

Msg#: 4434095 posted 11:36 pm on Mar 27, 2012 (gmt 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.


Msg#: 4434095 posted 10:22 pm on Mar 28, 2012 (gmt 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.

Global Options:
 top home search open messages active posts  

Home / Forums Index / Code, Content, and Presentation / JavaScript and AJAX
rss feed

All trademarks and copyrights held by respective owners. Member comments are owned by the poster.
Home ¦ Free Tools ¦ Terms of Service ¦ Privacy Policy ¦ Report Problem ¦ About ¦ Library ¦ Newsletter
WebmasterWorld is a Developer Shed Community owned by Jim Boykin.
© Webmaster World 1996-2014 all rights reserved