添加元素到DOM给定纯文本HTML只使用纯JavaScript(没有jQuery) [英] Add elements to the DOM given plain text HTML using only pure JavaScript (no jQuery)
问题描述
我需要能够向页面添加元素,给出HTML的原始文本字符串,包括任何数量的标签,属性等。理想情况下,我想要像任何一个格式正确的字符串HTML;
I need to be able to add elements to a page given a raw text string of HTML, including any number of tags, attributes etc. Ideally I would like to be able to do something like with any arbitrary string of well-formed html;
var theElement = document.createElement("<h1 id='title'>Some Title</h1><span style="display:inline-block; width=100px;">Some arbitrary text</span>");
document.getElementById("body").appendChild(theElement);
显然这不起作用,我正在寻找很好的方法来实现相同的结果。如果可能,我想避免解析HTML。我严格限制我可以使用的工具,没有jQuery或外部包含,必须跨浏览器和向后兼容到IE6。任何帮助将是巨大的。
Obviously that doesn't work, I'm looking for good ways to achieve the same result. I'd like to avoid parsing the HTML if possible. I'm severely restricted on the tools I can use, no jQuery or outside includes and must be cross-browser and backward compatible down to IE6. Any help would be huge.
推荐答案
尝试分配给 innerHTML
属性,并附加每个 children
。
Try assigning to the innerHTML
property of an anonymous element and appending each of its children
.
function appendHtml(el, str) {
var div = document.createElement('div');
div.innerHTML = str;
while (div.children.length > 0) {
el.appendChild(div.children[0]);
}
}
var html = '<h1 id="title">Some Title</h1><span style="display:inline-block; width=100px;">Some arbitrary text</span>';
appendHtml(document.body, html); // "body" has two more children - h1 and span.
这篇关于添加元素到DOM给定纯文本HTML只使用纯JavaScript(没有jQuery)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!