Creating a Bulleted List from JavaScript Data


var newItem = document.createElement("li"); var newText = document.createTextNode(data[i]); newItem.appendChild(newText); list.appendChild(newItem); 

Especially in the context with Web Services and AJAX (see Chapters 10 and 11), you often receive data from the server and have to display it in a dynamic way. One good approach is to use an HTML list. The following code provides a function createList() that expects an array with values and converts this into a list.

Creating a List (list.html)

<script language="JavaScript"   type="text/javascript"> function createList(data) {   var list = document.createElement("ul");   for (var i = 0; i < data.length; i++) {     var newItem = document.createElement("li");     var newText = document.createTextNode(data[i]);     newItem.appendChild(newText);     list.appendChild(newItem);   }   return list; } window.onload = function() {   var list = createList(     ["one", "two", "three", "four", "five"]);   document.body.appendChild(list); } </script> 

Note that document.body is a shortcut to the <body> element (otherwise, you could use document.getElementxByTagName("body")[0]); then appendChild() adds the HTML list to the end of the page.




JavaScript Phrasebook(c) Essential Code and Commands
JavaScript Phrasebook
ISBN: 0672328801
EAN: 2147483647
Year: 2006
Pages: 178

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net