Javascript - 将 HTML 附加到没有 innerHTML 的容器元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6304453/
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-23 21:11:49  来源:igfitidea点击:

Javascript - Append HTML to container element without innerHTML

javascripthtmlinnerhtml

提问by Bob

I need a way to append HTML to a container element without using innerHTML. The reason why I do not want to use innerHTML is because when it is use like this:

我需要一种不使用innerHTML 将HTML 附加到容器元素的方法。我不想使用innerHTML的原因是因为它是这样使用的:

element.innerHTML += htmldata

element.innerHTML += htmldata

It works by replacing all of the html first before adding the old html plus the new html. This is not good because it resets dynamic media such as embedded flash videos...

它的工作原理是先替换所有 html,然后再添加旧 html 和新 html。这不好,因为它会重置动态媒体,例如嵌入式 Flash 视频...

I could do it this way which works:

我可以通过这种方式做到这一点:

var e = document.createElement('span');
e.innerHTML = htmldata;
element.appendChild(e);

However the problem with that way is that there is that extra span tag in the document now which I do not want.

然而,这种方式的问题是文档中现在有我不想要的额外 span 标签。

How can this be done then? Thanks!

那怎么做呢?谢谢!

采纳答案by Felix Kling

To give an alternative (as using DocumentFragmentdoes not seem to work): You can simulate it by iterating over the children of the newly generated node and only append those.

给出一个替代方案(因为 usingDocumentFragment似乎不起作用):您可以通过迭代新生成节点的子节点来模拟它,并且只附加那些。

var e = document.createElement('div');
e.innerHTML = htmldata;

while(e.firstChild) {
    element.appendChild(e.firstChild);
}

回答by alnafie

I am surprised that none of the answers mentioned the insertAdjacentHTML()method. Check it out here. The first parameter is where you want the string appended and takes ("beforebegin", "afterbegin", "beforeend", "afterend"). In the OP's situation you would use "beforeend". The second parameter is just the html string.

我很惊讶没有一个答案提到该insertAdjacentHTML()方法。检查它在这里。第一个参数是您想要附加字符串并采用的位置(“beforebegin”、“afterbegin”、“beforeend”、“afterend”)。在 OP 的情况下,您将使用“beforeend”。第二个参数只是 html 字符串。

Basic usage:

基本用法:

var d1 = document.getElementById('one');
d1.insertAdjacentHTML('beforeend', '<div id="two">two</div>');

回答by Trevor Nestman

alnafie has a great answer for this question. I wanted to give an example of his code for reference:

alnafie 对这个问题有很好的回答。我想举一个他的代码示例以供参考:

var childNumber = 3;

function addChild() {
  var parent = document.getElementById('i-want-more-children');
  var newChild = '<p>Child ' + childNumber + '</p>';
  parent.insertAdjacentHTML('beforeend', newChild);
  childNumber++;
}
body {
  text-align: center;
}
button {
  background: rgba(7, 99, 53, .1);
  border: 3px solid rgba(7, 99, 53, 1);
  border-radius: 5px;
  color: rgba(7, 99, 53, 1);
  cursor: pointer;
  line-height: 40px;
  font-size: 30px;
  outline: none;
  padding: 0 20px;
  transition: all .3s;
}
button:hover {
  background: rgba(7, 99, 53, 1);
  color: rgba(255,255,255,1);
}
p {
  font-size: 20px;
  font-weight: bold;
}
<button type="button" onclick="addChild()">Append Child</button>
<div id="i-want-more-children">
  <p>Child 1</p>
  <p>Child 2</p>
</div>

Hopefully this is helpful to others.

希望这对其他人有帮助。

回答by vijay

<div id="Result">
</div>

<script>
for(var i=0; i<=10; i++){
var data = "<b>vijay</b>";
 document.getElementById('Result').innerHTML += data;
}
</script>

assign the data for div with "+=" symbol you can append data including previous html data

使用“+=”符号为 div 分配数据,您可以附加数据,包括以前的 html 数据

回答by Raynos

This is what DocumentFragmentwas meant for.

这就是DocumentFragment本意。

var frag = document.createDocumentFragment();
var span = document.createElement("span");
span.innerHTML = htmldata;
for (var i = 0, ii = span.childNodes.length; i < ii; i++) {
    frag.appendChild(span.childNodes[i]);
}
element.appendChild(frag);

document.createDocumentFragment, .childNodes

document.createDocumentFragment, .childNodes

回答by John

How to fish andwhile using strict code. There are two prerequisite functions needed at the bottom of this post.

如何钓鱼同时使用严格的代码。在这篇文章的底部需要两个先决条件函数。

xml_add('before', id_('element_after'), '<span xmlns="http://www.w3.org/1999/xhtml">Some text.</span>');

xml_add('after', id_('element_before'), '<input type="text" xmlns="http://www.w3.org/1999/xhtml" />');

xml_add('inside', id_('element_parent'), '<input type="text" xmlns="http://www.w3.org/1999/xhtml" />');

Add multiple elements (namespace only needs to be on the parent element):

添加多个元素(命名空间只需要在父元素上):

xml_add('inside', id_('element_parent'), '<div xmlns="http://www.w3.org/1999/xhtml"><input type="text" /><input type="button" /></div>');

Dynamic reusable code:

动态可重用代码:

function id_(id) {return (document.getElementById(id)) ? document.getElementById(id) : false;}

function xml_add(pos, e, xml)
{
 e = (typeof e == 'string' && id_(e)) ? id_(e) : e;

 if (e.nodeName)
 {
  if (pos=='after') {e.parentNode.insertBefore(document.importNode(new DOMParser().parseFromString(xml,'application/xml').childNodes[0],true),e.nextSibling);}
  else if (pos=='before') {e.parentNode.insertBefore(document.importNode(new DOMParser().parseFromString(xml,'application/xml').childNodes[0],true),e);}
  else if (pos=='inside') {e.appendChild(document.importNode(new DOMParser().parseFromString(xml,'application/xml').childNodes[0],true));}
  else if (pos=='replace') {e.parentNode.replaceChild(document.importNode(new DOMParser().parseFromString(xml,'application/xml').childNodes[0],true),e);}
  //Add fragment and have it returned.
 }
}