Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
133
rated 0 times [  134] [ 1]  / answers: 1 / hits: 26748  / 11 Years ago, thu, april 18, 2013, 12:00:00

First off sorry for this beginner question but I just recently learned JavaScript and I am now learning to develop Windows 8 apps. Here is the code in question:



        var numbers = [1, 2, 3, 4, 5];
id('numberList').innerHTML = '<ul>';
for (var x in numbers) {
id('numberList').innerHTML += '<li>' + x + '</li>';
}
id('numberList').innerHTML = '</ul>';


I have this in the ready function (for any Windows 8 developers) in my JS file and 'numbersList' refers to a section tag in the body (of the HTML file). The list does not show up at all when I am running the app. However when I simply try to add text instead of a list like so



       id('numberList').innerHTML = 'hello';


the text does show up. Could there be a problem with the way I am trying to insert the html elements?


More From » html

 Answers
241

You can't add pieces of illegal HTML like that. A <ul> tag with no </ul> is illegal. Build the entire HTML string in a string variable and then add one piece of legal HTML or build individual DOM elements, put the content in them and add them to the DOM.



Further, you don't iterate an array with for (var x in numbers) as that iterates properties of an object, not just array elements and, while it will work in some circumstances, is generally a bad practice that you should not use.



You can fix those errors and build up a single HTML string and then add it once at the end like this:



    var numbers = [1, 2, 3, 4, 5];
var str = '<ul>';
for (var x = 0; x < numbers.length; x++) {
str += '<li>' + numbers[x] + '</li>';
}
str += '</ul>';
id('numberList').innerHTML = str;


For completeness, you could also build individual DOM elements:



    var numbers = [1, 2, 3, 4, 5];
var ul = document.createElement(ul), li, tx;
for (var x = 0; x < numbers.length; x++) {
li = document.createElement(li);
tx = document.createTextNode(numbers[x]);
li.appendChild(tx);
ul.appendChild(li);
}
var parent = id('numberList');
parent.innerHTML = ;
parent.appendChild(ul);


You may also want to note that the code you original wrote was not retrieving the array elements numbers[x], but was using the array indexes x (which happen to be the same as the content so you wouldn't notice a difference in your sample code). Since that's probably not what you intended, you probably want to fix that too.


[#78820] Wednesday, April 17, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jayla

Total Points: 14
Total Questions: 96
Total Answers: 123

Location: Greenland
Member since Fri, Jul 31, 2020
4 Years ago
jayla questions
;