AppendChild to document.createDocumentFragment

AppendChild to document.createDocumentFragment

本文关键字:createDocumentFragment document to AppendChild      更新时间:2023-09-26

我有以下代码,我试图将嵌套的html组件附加到html元素

var docFrag = document.createDocumentFragment();
var count = 0;
arr.map(function(obj){
    count++;
    var title = obj.title;
    var codeAttr = obj.code;
    var htmlComponent = "<div class='line_h'><div class='floatRadio'><label for='radio_"+count+"'><input name='radio' value='"+codeAttr+"' id='radio_"+count+"' checked='checked' type='radio' class='inputRadio' /><span class='fld_lbl'>"+title+"</span></label></div></div>";
    console.log(htmlComponent);
    docFrag.appendChild(htmlComponent);
})

它通过一个对象数组进行迭代,我从中获得要添加到htmlComponent的内容。然而,当执行docFrag.appendChild(htmlComponent)时,它返回一个错误:

在'Node'上执行'appendChild'失败:参数1不是'Node'类型。

确实我正在传递一个字符串…我如何建立一个嵌套的html组件,并把它推到docFrag ?

必须首先将字符串转换为Nodes。使用这个函数:

function htmlToNodes(html, elementsOnly){
  if(typeof html != 'string') throw new Error('Argument must be a string');
  const template = document.createElement('template');
  template.innerHTML = html.trim();
  return elementsOnly ? template.content.children : template.content.childNodes;
}

然后将docFrag.appendChild(htmlComponent);替换为:

  htmlToNodes(htmlComponent).forEach((n)=>{
    docFrag.appendChild(n);
  };
相关文章:
  • 没有找到相关文章