我有一个表示元素的HTML字符串:“<li>text</li>”。我想将它附加到DOM中的一个元素(在我的例子中是一个ul)。如何使用Prototype或DOM方法做到这一点?

(我知道我可以在jQuery中轻松做到这一点,但不幸的是,我们没有使用jQuery。)


当前回答

这里有一个简单的方法:

String.prototype.toDOM=function(){
  var d=document
     ,i
     ,a=d.createElement("div")
     ,b=d.createDocumentFragment();
  a.innerHTML=this;
  while(i=a.firstChild)b.appendChild(i);
  return b;
};

var foo="<img src='//placekitten.com/100/100'>foo<i>bar</i>".toDOM();
document.body.appendChild(foo);

其他回答

我添加了一个Document原型,它从字符串创建一个元素:

Document.prototype.createElementFromString = function (str) {
   const element = new DOMParser().parseFromString(str, 'text/html');
   const child = element.documentElement.querySelector('body').firstChild;
   return child;
};

用法:

document.createElementFromString("<h1>Hello World!</h1>");

较新的DOM实现具有range.createContextualFragment,它以独立于框架的方式完成您所需的操作。

它得到了广泛的支持。不过,为了确保这一点,请在同一MDN链接中检查其兼容性,因为它会发生变化。截至2017年5月:

Feature         Chrome   Edge   Firefox(Gecko)  Internet Explorer   Opera   Safari
Basic support   (Yes)    (Yes)  (Yes)           11                  15.0    9.1.2

可以使用以下方法从字符串创建有效的DOM节点:

document.createRange().createContextualFragment()

以下示例在页面中添加一个按钮元素,从字符串中获取标记:

让html='<button type=“button”>单击我</按钮>';let fragmentFromString=函数(strHTML){return document.createRange().createContextualFragment(strHTML);}let fragment=fragmentFromString(html);document.body.appendChild(片段);

这是我的代码,它有效:

function parseTableHtml(s) { // s is string
    var div = document.createElement('table');
    div.innerHTML = s;

    var tr = div.getElementsByTagName('tr');
    // ...
}

我从这篇文章中得到了链接。(是否将HTML字符串转换为DOM元素?)

对我来说,我想找到一种将字符串转换为HTML元素的方法。如果您也有此需求,可以尝试以下方法

constfrag=document.createRange().createContextualFragment(`<a href=“/link.js”>js</a><a>去</a>`) constaCollection=frag.querySelectorAll(“a”)for(let[key,a]of Object.entries(aCollection)){console.log(a.getAttribute(“href”),a.textContent)}