将NodeList附加到HTML元素

cod*_*rMe 7 javascript dom

我有以下字符串:

var songlist = '<div class="list-item" id="57902ccae53fa51716424034"><div class="media"><img src="{imgsrc}" alt="Mama Tried" /></div><h4 class="title">Mama Tried</h4><div class="song-controls"><button class="song play"><span class="fa fa-play"></button></div></div><div class="list-item" id="57902cddae7b54e264fcc6e4"><div class="media"><img src="{imgsrc}" alt="Blue Eyes Crying In the Rain" /></div><h4 class="title">Blue Eyes Crying In the Rain</h4><div class="song-controls"><button class="song play"><span class="fa fa-play"></button></div></div>';
Run Code Online (Sandbox Code Playgroud)

我通过这个自定义函数转换为NodeList:

var toDom = function(str) {
  var tmp = document.createElement("div");
  tmp.innerHTML = str;
  return tmp.childNodes;
};
Run Code Online (Sandbox Code Playgroud)

console.log(toDom(songlist))输出NodeList [ <div#57902ccae53fa51716424034.list-item>, <div#57902cddae7b54e264fcc6e4.list-item> ],您可以浏览devtools.

当我尝试将集合追加到节点时...

document.getElementById("app-data").appendChild(toDom(songlist));
Run Code Online (Sandbox Code Playgroud)

我知道TypeError: Argument 1 of Node.appendChild does not implement interface Node.哪个是奇怪的,因为说明参数1 的文档Node.appendChild()必须是Node类型.

那么,Node.appendChild()期望什么类型的元素呢?我也试过HTMLCollection.

见JSFiddle.

马长昆*_*man 10

现在,您可以直接使用 element.append() 和 element.childNodes 。就像:

var container = document.getElementById("app-data");
var childNodes = toDom(songlist);
container.append(...childNodes)
function toDom(str) {
  var tmp = document.createElement("div");
  tmp.innerHTML = str;
  return tmp.childNodes;
};

Run Code Online (Sandbox Code Playgroud)


dfs*_*fsq 8

问题是Node.childNodesNodeList.因此,当您尝试追加它时,它当然会失败,因为NodeList与Node不同.您可以在循环中逐个追加子节点:

var container = document.getElementById("app-data");
var childNodes = toDom(songlist);

for (var i = 0; i < childNodes.length; i++) {
    container.appendChild(childNodes[i])
}
Run Code Online (Sandbox Code Playgroud)

  • 应使用文档片段而不是多个追加。请参阅/sf/answers/1043721591/ (2认同)