我有一个表示元素的HTML字符串:“<li>text</li>”。我想将它附加到DOM中的一个元素(在我的例子中是一个ul)。如何使用Prototype或DOM方法做到这一点?
(我知道我可以在jQuery中轻松做到这一点,但不幸的是,我们没有使用jQuery。)
我有一个表示元素的HTML字符串:“<li>text</li>”。我想将它附加到DOM中的一个元素(在我的例子中是一个ul)。如何使用Prototype或DOM方法做到这一点?
(我知道我可以在jQuery中轻松做到这一点,但不幸的是,我们没有使用jQuery。)
当前回答
可以使用以下方法从字符串创建有效的DOM节点:
document.createRange().createContextualFragment()
以下示例在页面中添加一个按钮元素,从字符串中获取标记:
让html='<button type=“button”>单击我</按钮>';let fragmentFromString=函数(strHTML){return document.createRange().createContextualFragment(strHTML);}let fragment=fragmentFromString(html);document.body.appendChild(片段);
其他回答
我添加了一个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节点:
document.createRange().createContextualFragment()
以下示例在页面中添加一个按钮元素,从字符串中获取标记:
让html='<button type=“button”>单击我</按钮>';let fragmentFromString=函数(strHTML){return document.createRange().createContextualFragment(strHTML);}let fragment=fragmentFromString(html);document.body.appendChild(片段);
解决方案-适用于自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);
var msg=“测试”jQuery.parseHTML(消息)
为什么不使用原生js?
var s="<span class='text-muted' style='font-size:.75em; position:absolute; bottom:3px; left:30px'>From <strong>Dan's Tools</strong></span>"
var e=document.createElement('div')
var r=document.createRange();
r.selectNodeContents(e)
var f=r.createContextualFragment(s);
e.appendChild(f);
e = e.firstElementChild;