仅使用纯JavaScript(不使用jQuery)将元素添加到给定纯文本HTML的DOM中
我需要能够在给定HTML原始文本字符串的情况下向页面添加元素,包括任意数量的标记,属性等。
var theElement = document.createElement("
Some Title
Some arbitrary text");document.getElementById("body").appendChild(theElement);
显然那是行不通的,我正在寻找实现相同结果的好方法。 如果可能,我想避免解析HTML。 我在可以使用的工具上受到严格限制,没有jQuery或外部包含,并且必须跨浏览器并且向下兼容IE6。 任何帮助都是巨大的。
kirps asked 2020-06-17T10:03:56Z
5个解决方案
72 votes
尝试分配给匿名元素的children属性,并附加其每个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 = '
Some Title
Some arbitrary text';appendHtml(document.body, html); // "body" has two more children - h1 and span.
maerics answered 2020-06-17T10:04:11Z
14 votes
var el = document.createElement("h1")
el.id="title";
el.innerHTML = "Some title";
document.body.appendChild(el);
var el2 = document.createElement("span")
el2.style.display="block";
el2.style.width="100%";
el2.innerHTML = "Some arb text";
document.body.appendChild(el2);
应该工作(小提琴:[http://jsfiddle.net/gWHVy/)]
编辑:这是一种特殊情况的解决方案,因为您知道要插入的直接子项的属性。看看在一般情况下都可以使用的Aaron解决方案。
beardhatcode answered 2020-06-17T10:04:35Z
11 votes
您可以使用+=:
document.body.insertAdjacentHTML("beforeend", theHTMLToInsert);
除了+=之外,还有其他选项,但是听起来您想附加到元素,这就是innerHTML所做的。
现场示例:
+=
+=
与使用+=和innerHTML不同,这不需要浏览器浏览元素的内容并创建表示该元素的HTML字符串,销毁这些元素(包括它们所具有的任何事件处理程序),并用相同的替换 元素加上您的添加物。 它只是添加您的添加内容,而使现有内容保持不变。
T.J. Crowder answered 2020-06-17T10:06:13Z
6 votes
您可以获取要在其下插入HTML的元素的elementId,并使用innerHTML来添加html。
document.getElementById("body").innerHTML = "
Some Title
test";Vivek Viswanathan answered 2020-06-17T10:06:37Z
3 votes
Maerics解决方案立即解决了我的问题。 但是,我需要对其进行快速调整以执行所需的操作。我有几个脚本和样式表可在单击时加载。 我无法将脚本或样式表添加为DOM后加载的实际对象。 如果将innerHTML设置为document.body包含部分,则它将仅打印文本,浏览器不会将其识别为链接对象。 为了解决这个问题,我使用了以下代码。
function appendHtml(el, str) {
var div = document.createElement('div');
div.innerHTML = str;
while (div.children.length > 0) {
if ( div.children[0].tagName == 'LINK' ) {
// Create an actual link element to append later
style = document.createElement('link');
style.href = div.children[0].href;
// append your other things like rel, type, etc
el.appendChild(style);
}
el.appendChild(div.children[0]);
}
}
Aaron answered 2020-06-17T10:06:57Z