我有一个表示元素的HTML字符串:“<li>text</li>”。我想将它附加到DOM中的一个元素(在我的例子中是一个ul)。如何使用Prototype或DOM方法做到这一点?
(我知道我可以在jQuery中轻松做到这一点,但不幸的是,我们没有使用jQuery。)
我有一个表示元素的HTML字符串:“<li>text</li>”。我想将它附加到DOM中的一个元素(在我的例子中是一个ul)。如何使用Prototype或DOM方法做到这一点?
(我知道我可以在jQuery中轻松做到这一点,但不幸的是,我们没有使用jQuery。)
当前回答
实际上,我想我会分享我想出的这个过于复杂但又简单的方法。。。也许有人会发现有用的东西。
/*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')"
}));
其他回答
使用insertAdjacentHTML()。它适用于所有当前浏览器,即使是IE11。
var mylist=文档.getElementById('mylist');mylist.insertAdjacentHTML('beforeend','<li>third</li>');<ul id=“mylist”><li>第一个</li><li>第二个</li></ul>
参观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;
}
function domify (str) {
var el = document.createElement('div');
el.innerHTML = str;
var frag = document.createDocumentFragment();
return frag.appendChild(el.removeChild(el.firstChild));
}
var str = "<div class='foo'>foo</div>";
domify(str);
我自己找了很多,找到了一个很好的解决方案。
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>
从字符串渲染DOM的最快解决方案:
let render = (relEl, tpl, parse = true) => {
if (!relEl) return;
const range = document.createRange();
range.selectNode(relEl);
const child = range.createContextualFragment(tpl);
return parse ? relEl.appendChild(child) : {relEl, el};
};
在这里,您可以检查DOM操作React与原生JS的性能
现在您可以简单地使用:
let element = render(document.body, `
<div style="font-size:120%;line-height:140%">
<p class="bold">New DOM</p>
</div>
`);
当然,在不久的将来,您将使用来自内存的引用,因为var“element”是您在文档中新创建的DOM。
记住“innerHTML=”非常慢:/