我有一个表示元素的HTML字符串:“<li>text</li>”。我想将它附加到DOM中的一个元素(在我的例子中是一个ul)。如何使用Prototype或DOM方法做到这一点?
(我知道我可以在jQuery中轻松做到这一点,但不幸的是,我们没有使用jQuery。)
我有一个表示元素的HTML字符串:“<li>text</li>”。我想将它附加到DOM中的一个元素(在我的例子中是一个ul)。如何使用Prototype或DOM方法做到这一点?
(我知道我可以在jQuery中轻松做到这一点,但不幸的是,我们没有使用jQuery。)
当前回答
参观https://www.codegrepper.com/code-examples/javascript/convert+a+字符串+to+html+元素+in+js
const stringToHtml = function (str) {
var parser = new DOMParser();
var doc = parser.parseFromString(str, 'text/html');
return doc.body;
}
其他回答
参观https://www.codegrepper.com/code-examples/javascript/convert+a+字符串+to+html+元素+in+js
const stringToHtml = function (str) {
var parser = new DOMParser();
var doc = parser.parseFromString(str, 'text/html');
return doc.body;
}
答复
创建模板将模板的innerHTML设置为strim.trim()创建模板的子级数组返回子项、子项或
函数toElement(s=“”,c,t=document.createElement('template'),l='length'){t.innerHTML=s.trim();c=[…t.content.childNodes];返回c[l]>1?c: c[0]| |“”;}console.log(toElement());console.log(toElement(“”));console.log(toElement(“”));console.log(toElement('<td>With td</td>'));console.log(toElement('<tr><td>With t</td></tr>'));console.log(toElement('<tr><td>foo</td></tr><tr><td>bar</td></tr>'));console.log(toElement('<div><span><span>嵌套</span><span>填充</span></div>'));
实际上,我想我会分享我想出的这个过于复杂但又简单的方法。。。也许有人会发现有用的东西。
/*Creates a new element - By Jamin Szczesny*/
function _new(args){
ele = document.createElement(args.node);
delete args.node;
for(x in args){
if(typeof ele[x]==='string'){
ele[x] = args[x];
}else{
ele.setAttribute(x, args[x]);
}
}
return ele;
}
/*You would 'simply' use it like this*/
$('body')[0].appendChild(_new({
node:'div',
id:'my-div',
style:'position:absolute; left:100px; top:100px;'+
'width:100px; height:100px; border:2px solid red;'+
'cursor:pointer; background-color:HoneyDew',
innerHTML:'My newly created div element!',
value:'for example only',
onclick:"alert('yay')"
}));
解决方案-适用于自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);
这里有一个简单的方法:
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);