使用javascript显示[object HTMLUListElement]的内容

Chr*_*and 2 html javascript html-lists

我有一个 javascript 函数,它基于传入的数组生成一个 ul 列表,使用与此类似的方法 -创建一个 <ul> 并根据传递的数组填充它

但是,当我执行以下操作时...

document.getElementById("list").innerHTML = generateListFromArray(array);
Run Code Online (Sandbox Code Playgroud)

打印出来的只是

[object HTMLUListElement]
Run Code Online (Sandbox Code Playgroud)

谁能告诉我如何将内容作为 HTML 打印到 div 中?

T.J*_*der 6

您正在创建一个合适的 UL 元素 ( HTMLUListElement),这很棒。您可以通过简单地将其附加到您的目标来直接使用它:

document.getElementById("list").appendChild(generateListFromArray(array));
Run Code Online (Sandbox Code Playgroud)

如果目标已经包含要替换(而不是添加到)的内容,您可以先清除目标元素:

var list = document.getElementById("list");     // Get the target element
list.innerHTML = "";                            // Remove previous content
list.appendChild(generateListFromArray(array)); // Append your generated UL
Run Code Online (Sandbox Code Playgroud)

根本没有理由首先将您创建的元素转换为标记(通过使用.innerHTML.outerHTML的返回值generateListFromArray)。

如果 list也是 aul并且你想替换它,你可以用insertBeforeand做到这一点removeChild

var list = document.getElementById("list");     // Get the target element
var parent = list.parentNode;                   // Get its parent
var newList = generateListFromArray(array);     // Get the new one
parent.insertBefore(
    newList,                                    // Insert the new list...
    list                                        // ...before the old one
);
parent.removeChild(list);                       // Remove the old
newList.id = "list";                            // Give the new list the ID the
                                                // old one had
Run Code Online (Sandbox Code Playgroud)