javascript - innerHTML adds text but not html tags -
first off sorry beginner question learned javascript , learning develop windows 8 apps. here code in question:
var numbers = [1, 2, 3, 4, 5]; id('numberlist').innerhtml = '<ul>'; (var x in numbers) { id('numberlist').innerhtml += '<li>' + x + '</li>'; } id('numberlist').innerhtml = '</ul>';
i have in "ready" function (for windows 8 developers) in js file , 'numberslist' refers section tag in body (of html file). list not show @ when running app. when try add text instead of list so
id('numberlist').innerhtml = 'hello';
the text show up. there problem way trying insert html elements?
you can't add pieces of illegal html that. <ul>
tag no </ul>
illegal. build entire html string in string variable , add 1 piece of legal html or build individual dom elements, put content in them , add them dom.
further, don't iterate array for (var x in numbers)
iterates properties of object, not array elements and, while work in circumstances, bad practice should not use.
you can fix errors , build single html string , add once @ end this:
var numbers = [1, 2, 3, 4, 5]; var str = '<ul>'; (var x = 0; x < numbers.length; x++) { str += '<li>' + numbers[x] + '</li>'; } str += '</ul>'; id('numberlist').innerhtml = str;
for completeness, build individual dom elements:
var numbers = [1, 2, 3, 4, 5]; var ul = document.createelement("ul"), li, tx; (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 want note code original wrote not retrieving array elements numbers[x]
, using array indexes x
(which happen same content wouldn't notice difference in sample code). since that's not intended, want fix too.
Comments
Post a Comment