我有一个表示元素的HTML字符串:“<li>text</li>”。我想将它附加到DOM中的一个元素(在我的例子中是一个ul)。如何使用Prototype或DOM方法做到这一点?
(我知道我可以在jQuery中轻松做到这一点,但不幸的是,我们没有使用jQuery。)
我有一个表示元素的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);
其他回答
解决方案-适用于自IE 4.0以来的所有浏览器
var htmlString = `<body><header class="text-1">Hello World</header><div id="table"><!--TABLE HERE--></div></body>`;
var tableString = `<table class="table"><thead><tr><th>th cell</th></tr></thead><tbody><tr><td>td cell</td></tr></tbody></table>`;
var doc = document.implementation.createHTMLDocument();
doc.open();
doc.write(htmlString);
doc.getElementById('table').insertAdjacentHTML('beforeend', tableString);
doc.close();
console.log(doc);
或者你可以使用DOMParser
var doc = (new DOMParser).parseFromString(htmlString, "text/html");
doc.getElementById('table').insertAdjacentHTML('beforeend', tableString);
console.log(doc);
我自己找了很多,找到了一个很好的解决方案。
const stringToHTML = (str) => {
var parser = new DOMParser();
var doc = parser.parseFromString(str, 'text/html');
return doc.body;
};
要转换的字符串:
'<iframe src="https://player.vimeo.com/video/578680903?h=ea840f9223&app_id=122963" width="640" height="360" frameborder="0" allow="autoplay; fullscreen; picture-in-picture" allowfullscreen title="Total Body Balance"></iframe>'
结果:
<body><iframe src="https://player.vimeo.com/video/578680903?h=ea840f9223&app_id=122963" width="640" height="360" frameborder="0" allow="autoplay; fullscreen; picture-in-picture" allowfullscreen="" title="Total Body Balance"></iframe></body>
使用insertAdjacentHTML()。它适用于所有当前浏览器,即使是IE11。
var mylist=文档.getElementById('mylist');mylist.insertAdjacentHTML('beforeend','<li>third</li>');<ul id=“mylist”><li>第一个</li><li>第二个</li></ul>
您可以使用以下函数将文本“HTML”转换为元素
函数htmlToElement(html){var element=document.createElement('div');element.innerHTML=html;返回(元素);}var html=“<li>text和html</li>”;var e=htmlToElement(html);
较新的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