将元素添加到 DOM 给定的纯文本 HTML 中,仅使用纯 JavaScript(没有 jQuery)

Add elements to the DOM given plain text HTML using only pure JavaScript (no jQuery)

本文关键字:JavaScript jQuery 没有 HTML 添加 元素 DOM 文本      更新时间:2023-09-26

我需要能够在给定HTML原始文本字符串的情况下向页面添加元素,包括任意数量的标签,属性等。 理想情况下,我希望能够对任何格式良好的 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。任何帮助都是巨大的。

尝试分配给匿名元素的 innerHTML 属性并附加其每个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.

您可以使用insertAdjacentHTML

document.body.insertAdjacentHTML("beforeend", theHTMLToInsert);

除了 beforeend 之外还有其他选项,但听起来您想附加到元素中,这就是beforeend的作用。

现场示例:

document.body.insertAdjacentHTML("beforeend", "<div>This is the new content.</div>");
<div>Existing content in <code>body</code>.</div>

与将+=innerHTML一起使用不同,这不需要浏览器旋转元素的内容并创建一个HTML字符串来表示它,销毁这些元素(包括它们上的任何事件处理程序),并将它们替换为相同的元素加上您的添加。它只是添加您的添加内容,而现有内容保持不变。

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 解决方案。

您可以获取要插入 HTML 的元素的 elementId,并使用 innerHTML 添加 html。

document.getElementById("body").innerHTML = "<h1 id='title'>Some Title</h1><span>test</span>";

maerics 解决方案立即解决了我的问题。但是,我需要对其进行快速调整以完成我需要的操作。我有几个脚本和样式表,可以在单击时加载。我无法将脚本或样式表作为实际对象添加到 DOM 加载后。如果您将 document.body 的 innerHTML 设置为包含<link rel="stylesheet" />部分,它只会打印文本,浏览器不会将其识别为链接对象。为了解决这个问题,我使用了以下代码。

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]);
  }
}