我有一个 javascript 函数,它基于使用与此类似的方法传入的数组生成一个 ul 列表 - Create a <ul> and fill it based on a passed array
但是,当我执行以下操作时......
document.getElementById("list").innerHTML = generateListFromArray(array);
所有被打印的是
[object HTMLUListElement]
谁能告诉我如何将内容作为 HTML 打印到 div 中?
最佳答案
您正在创建一个合适的 UL 元素 (HTMLUListElement
),这很棒。您可以直接使用它,只需将它附加到您的目标即可:
document.getElementById("list").appendChild(generateListFromArray(array));
如果目标已经包含您想要替换(而不是添加)的内容,您可以先清除目标元素:
var list = document.getElementById("list"); // Get the target element
list.innerHTML = ""; // Remove previous content
list.appendChild(generateListFromArray(array)); // Append your generated UL
根本没有理由首先将您创建的元素转换为标记(通过在 的返回值上使用
)..innerHTML
或 .outerHTML
generateListFromArray
如果 list
也是一个 ul
并且您想替换它,您可以使用 insertBefore
和 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
关于javascript - 使用 javascript 显示 [object HTMLUListElement] 的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38240544/