我有一个表示元素的HTML字符串:“<li>text</li>”。我想将它附加到DOM中的一个元素(在我的例子中是一个ul)。如何使用Prototype或DOM方法做到这一点?
(我知道我可以在jQuery中轻松做到这一点,但不幸的是,我们没有使用jQuery。)
我有一个表示元素的HTML字符串:“<li>text</li>”。我想将它附加到DOM中的一个元素(在我的例子中是一个ul)。如何使用Prototype或DOM方法做到这一点?
(我知道我可以在jQuery中轻松做到这一点,但不幸的是,我们没有使用jQuery。)
当前回答
我添加了一个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
这是我的代码,它有效:
function parseTableHtml(s) { // s is string
var div = document.createElement('table');
div.innerHTML = s;
var tr = div.getElementsByTagName('tr');
// ...
}
这里有一个简单的方法:
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);
可以使用以下方法从字符串创建有效的DOM节点:
document.createRange().createContextualFragment()
以下示例在页面中添加一个按钮元素,从字符串中获取标记:
让html='<button type=“button”>单击我</按钮>';let fragmentFromString=函数(strHTML){return document.createRange().createContextualFragment(strHTML);}let fragment=fragmentFromString(html);document.body.appendChild(片段);
HTML5和ES6
<模板>
Demo
“使用严格”;/****@作者xgqfrms*@许可证MIT*@版权xgqfrms*@description HTML5模板*@扩增*@示例**//*<模板><h2>鲜花</h2><img src=“https://www.w3schools.com/tags/img_white_flower.jpg"></template><模板><div class=“myClass”>我喜欢:</div></template>*/常量showContent=()=>{//let temp=document.getElementsByTagName(“template”)[0],let temp=document.querySelector(`[data tempalte=“tempalte img”]`),clone=临时内容克隆节点(true);document.body.appendChild(克隆);};const templateGenerator=(datas=[],debug=false)=>{让result=``;//let temp=document.getElementsByTagName(“template”)[1],let temp=document.querySelector(`[data tempalte=“tempalte links”]`),item=temp.content.querySelector(“div”);for(设i=0;i<data.length;i++){let a=document.importNode(item,true);a.textContent+=数据[i];document.body.appendChild(a);}返回结果;};const arr=[“奥迪”、“宝马”、“福特”、“本田”、“捷豹”、“日产”];if(document.createElement(“template”).content){console.log(“是!浏览器支持模板元素”);模板生成器(arr);setTimeout(()=>{showContent();}, 0);}其他{console.error(“否!浏览器不支持模板元素”);}@字符集“UTf-8”;/*测试.css*/:根目录{--颜色:#000;--默认cololr:#fff;--新的cololr:#0f0;}[数据class=“links”]{颜色:白色;背景色:道奇蓝;填充:20px;文本对齐:居中;边距:10px;}<!DOCTYPE html><html lang=“zh-Hans”><head><meta charset=“UTF-8”><meta name=“viewport”content=“width=设备宽度,初始比例=1.0”><meta http equiv=“X-UA-Compatible”content=“ie=edge”><title>模板测试</title><!--[如果lt IE 9]><script src=“https://cdnjs.cloudflare.com/ajax/libs/html5shiv/3.7.3/html5shiv.js“></script><![endif]--></head><body><章节><h1>模板测试</h1></section><template data tempalte=“tempalte img”><h3>花卉图像</h3><img src=“https://www.w3schools.com/tags/img_white_flower.jpg"></template><template data tempalte=“tempalte links”><h3>链接</h3>我喜欢:</div></template><!-- js--></body></html>