将HTMLDocument转换/解析为HTMLElement

时间:2016-05-24 17:07:38

标签: javascript dom

我有以下功能:

function append(htmlString,parentElem){
  var parser = new DOMParser();
  var childElem = parser.parseFromString(htmlString, "text/html");
  parentElem.appendChild(childElem);
}

此函数获取html字符串和父元素。我正在使用DOMParser解析html字符串。当我尝试将childElem附加到parentElem时,会出现错误。

在谷歌搜索后,我发现appendChild函数需要HTMLElementchildElemHTMLDocument的实例。

如何将childElem转换/转换/解析为HTMLElement

1 个答案:

答案 0 :(得分:2)

  

如何将childElem转换/转换/解析为HTMLElement

(请参阅下面的然而 <)>

你不想。相反,请追加documentElement,或更可能追加其childNodes元素的body

function append(htmlString,parentElem){
  var parser = new DOMParser();
  var doc = parser.parseFromString(htmlString, "text/html");
  parentElem.appendChild(doc.documentElement);
}

function append(htmlString, parentElem) {
  var parser = new DOMParser();
  var doc = parser.parseFromString(htmlString, "text/html");
  parentElem.appendChild(doc.documentElement);
}
append("<span>New stuff added via <code>append</code></span>", document.getElementById("target"));
<div id="target">Stuff already in the target element.</div>

请注意它是如何偏移的,因为我们实际上最后添加了一个重复的body元素。

相反,我们做了子节点:

function append(htmlString,parentElem){
  var parser = new DOMParser();
  var doc = parser.parseFromString(htmlString, "text/html");
  var nextNode;
  for (var node = doc.documentElement.firstChild; node; node = nextNode) {
      nextNode = node.nextSibling;
      parentElem.appendChild(node);
  }
}

function append(htmlString,parentElem){
  var parser = new DOMParser();
  var doc = parser.parseFromString(htmlString, "text/html");
  var nextNode;
  for (var node = doc.body.firstChild; node; node = nextNode) {
      nextNode = node.nextSibling;
      parentElem.appendChild(node);
  }
}
append("<span>New stuff added via <code>append</code></span>", document.getElementById("target"));
<div id="target">Stuff already in the target element.</div>

但是,现代浏览器上有一个内置方法可以为您完成这项工作,名为insertAdjacentHTML

function append(htmlString,parentElem){
    parentElem.insertAdjacentHTML("beforeend", htmlString);
}

function append(htmlString,parentElem){
    parentElem.insertAdjacentHTML("beforeend", htmlString);
}
append("<span>New stuff added via <code>append</code></span>", document.getElementById("target"));
<div id="target">Stuff already in the target element.</div>