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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10309650/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 00:47:49  来源:igfitidea点击:

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

javascripthtmldom

提问by kirps

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;

我需要能够在给定 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);

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.

显然这不起作用,我正在寻找实现相同结果的好方法。如果可能,我想避免解析 HTML。我可以使用的工具受到严格限制,没有 jQuery 或外部包含,并且必须跨浏览器并向后兼容到 IE6。任何帮助都会是巨大的。

回答by maerics

Try assigning to the innerHTMLpropertyof an anonymous element and appending each of its children.

尝试分配给匿名元素的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.

回答by beardhatcode

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

Shoud work (fiddle: http://jsfiddle.net/gWHVy/)

应该工作(小提琴:http: //jsfiddle.net/gWHVy/

edit:This is a solution for the special case that you know the properties of direct children of what you want to insert. Take a look at the solution of Aaronthat works in the general case.

编辑:这是一种特殊情况的解决方案,即您知道要插入的内容的直接子项的属性。看一下Aaron解决方案,它适用于一般情况。

回答by T.J. Crowder

You can use insertAdjacentHTML:

您可以使用insertAdjacentHTML

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

There are options other than beforeend, but it sounds like you want to append to the element, which is what beforeenddoes.

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

Live Example:

现场示例:

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

Unlike using +=with innerHTML, this doesn't require the browser to spin through the content of the element and create an HTML string to represent it, destroy those elements (including any event handlers they have on them), and replace them with the same elements plus your additions. It just adds your additions, leaving the existing content unchanged.

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

回答by Vivek Viswanathan

You could get the elementId of the element under which you wish to insert the HTML and use innerHTML for adding the html.

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

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

回答by Aaron

maerics solution fixed my problem straight away. I however needed to make a quick tweak to it to do what I needed. I have several scripts and stylesheets that load on click. I can't add either scripts or stylesheets as actual objects to the DOM post-load. If you set innerHTML for say, document.body, to contain the <link rel="stylesheet" />part, it will only print the text and the browser will not recognize it as a link object. To fix this, I used the following code.

maerics 解决方案立即解决了我的问题。但是,我需要对其进行快速调整以完成我需要的操作。我有几个脚本和样式表可以在点击时加载。我无法将脚本或样式表作为实际对象添加到 DOM 后加载。如果您将innerHTML 设置为document.body,以包含该<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]);
  }
}