innerHTML adds text but not html tags

北城余情 提交于 2019-12-03 17:18:04

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.

You should never use += with innerHTML. Instead, build the string and then put it in all at once, otherwise the engine will try to correct your incomplete HTML.

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

With that being said, a "better" way to do it would be as follows:

var numbers = [1,2,3,4,5], ul = document.createElement('ul');
for( var x in numbers) ul.appendChild(document.createElement('li')).appendChild(document.createTextNode(x));
var nl = id("numberList");
while(nl.firstChild) nl.removeChild(nl.firstChild);
nl.appendChild(ul);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!