Javascript 将 HTML 字符串附加到 DOM
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7327056/
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
Appending HTML string to the DOM
提问by ?ime Vidas
How to append this HTML string
如何附加此 HTML 字符串
var str = '<p>Just some <span>text</span> here</p>';
to the DIV with the ID 'test'
which is in the DOM?
到具有'test'
DOM 中ID 的 DIV ?
(Btw div.innerHTML += str;
is not acceptable.)
(顺便说一句div.innerHTML += str;
是不可接受的。)
回答by Neil
Use insertAdjacentHTML
if it's available, otherwise use some sort of fallback. insertAdjacentHTML is supported in all current browsers.
使用insertAdjacentHTML
(如果可用),否则使用某种回退。当前所有浏览器都支持insertAdjacentHTML 。
div.insertAdjacentHTML( 'beforeend', str );
Live demo:http://jsfiddle.net/euQ5n/
现场演示:http : //jsfiddle.net/euQ5n/
回答by alex
Is this acceptable?
这是可以接受的吗?
var child = document.createElement('div');
child.innerHTML = str;
child = child.firstChild;
document.getElementById('test').appendChild(child);
But, Neil's answeris a better solution.
但是,尼尔的答案是更好的解决方案。
回答by Kamil Kie?czewski
Performance
表现
AppendChild
(E) is more than 2x faster than other solutions on chrome and safari, insertAdjacentHTML
(F) is fastest on firefox. The innerHTML=
(B) (do not confuse with +=
(A)) is second fast solution on all browsers and it is much more handy than E and F.
AppendChild
(E) 在 chrome 和 safari 上比其他解决方案快 2 倍以上,insertAdjacentHTML
(F) 在 Firefox 上最快。在innerHTML=
(B)(不要混淆+=
(A))是在所有的浏览器第二快速的解决方案,这是更方便的比E和F.
Details
细节
Set up environment (2019.07.10) MacOs High Sierra 10.13.4 on Chrome 75.0.3770 (64-bit), Safari 11.1.0 (13604.5.6), Firefox 67.0.0 (64-bit)
设置环境 (2019.07.10) MacOs High Sierra 10.13.4 on Chrome 75.0.3770 (64-bit), Safari 11.1.0 (13604.5.6), Firefox 67.0.0 (64-bit)
- on Chrome E (140k operations per second) is fastest, B (47k) and F (46k) are second, A (332) is slowest
- on firefox F (94k) is fastest, then B(80k), D (73k), E(64k), C (21k) slowest is A(466)
- on Safari E(207k) is fastest, then B(89k), F(88k), D(83k), C (25k), slowest is A(509)
- 在 Chrome E(每秒 140k 次操作)上最快,B (47k) 和 F (46k) 次之,A (332) 最慢
- 在firefox上F(94k)最快,然后B(80k),D(73k),E(64k),C(21k)最慢是A(466)
- 在 Safari 上 E(207k) 最快,然后是 B(89k)、F(88k)、D(83k)、C (25k),最慢的是 A(509)
You can replay test in your machine here
您可以在此处在您的机器上重播测试
function A() {
container.innerHTML += '<p>A: Just some <span>text</span> here</p>';
}
function B() {
container.innerHTML = '<p>B: Just some <span>text</span> here</p>';
}
function C() {
$('#container').append('<p>C: Just some <span>text</span> here</p>');
}
function D() {
var p = document.createElement("p");
p.innerHTML = 'D: Just some <span>text</span> here';
container.appendChild(p);
}
function E() {
var p = document.createElement("p");
var s = document.createElement("span");
s.appendChild( document.createTextNode("text ") );
p.appendChild( document.createTextNode("E: Just some ") );
p.appendChild( s );
p.appendChild( document.createTextNode(" here") );
container.appendChild(p);
}
function F() {
container.insertAdjacentHTML('beforeend', '<p>F: Just some <span>text</span> here</p>');
}
A();
B();
C();
D();
E();
F();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
This snippet only for show code used in test (in jsperf.com) - it not perform test itself.
<div id="container"></div>
回答by Chris Calo
The idea is to use innerHTML
on an intermediary element and then move all of its child nodes to where you really want them via appendChild
.
这个想法是innerHTML
在中间元素上使用,然后将其所有子节点通过appendChild
.
var target = document.getElementById('test');
var str = '<p>Just some <span>text</span> here</p>';
var temp = document.createElement('div');
temp.innerHTML = str;
while (temp.firstChild) {
target.appendChild(temp.firstChild);
}
This avoids wiping out any event handlers on div#test
but still allows you to append a string of HTML.
这避免了清除任何事件处理程序,div#test
但仍允许您附加一串 HTML。
回答by hsivonen
The right way is using insertAdjacentHTML
. In Firefox earlier than 8, you can fall back to using Range.createContextualFragment
if your str
contains no script
tags.
正确的方法是使用insertAdjacentHTML
. 在 Firefox 8 之前的版本中,Range.createContextualFragment
如果str
不包含script
标签,您可以回退使用。
If your str
contains script
tags, you need to remove script
elements from the fragment returned by createContextualFragment
before inserting the fragment. Otherwise, the scripts will run. (insertAdjacentHTML
marks scripts unexecutable.)
如果您的str
containsscript
标签,则需要在插入片段之前script
从返回的片段中删除元素createContextualFragment
。否则,脚本将运行。(insertAdjacentHTML
标记脚本不可执行。)
回答by J.M.I. MADISON
Quick Hack:
快速破解:
<script>
document.children[0].innerHTML="<h1>QUICK_HACK</h1>";
</script>
Use Cases:
用例:
1: Save as .html file and run in chrome or firefox or edge. (IE wont work)
1:另存为.html文件并在chrome或firefox或edge中运行。(IE 不起作用)
2: Use in http://js.do
2:在http://js.do中使用
In Action:http://js.do/HeavyMetalCookies/quick_hack
在行动:http : //js.do/HeavyMetalCookies/quick_hack
Broken down with comments:
用评论分解:
<script>
//: The message "QUICK_HACK"
//: wrapped in a header #1 tag.
var text = "<h1>QUICK_HACK</h1>";
//: It's a quick hack, so I don't
//: care where it goes on the document,
//: just as long as I can see it.
//: Since I am doing this quick hack in
//: an empty file or scratchpad,
//: it should be visible.
var child = document.children[0];
//: Set the html content of your child
//: to the message you want to see on screen.
child.innerHTML = text;
</script>
Reason Why I posted:
我发帖的原因:
JS.do has two must haves:
JS.do 有两个必备品:
- No autocomplete
- Vertical monitor friendly
- 没有自动完成
- 垂直显示器友好
But doesn't show console.log messages. Came here looking for a quick solution. I just want to see the results of a few lines of scratchpad code, the other solutions are too much work.
但不显示 console.log 消息。来到这里寻找快速解决方案。我只是想看看几行scratchpad代码的结果,其他的解决方法工作量太大了。
回答by Nick Brunt
Why is that not acceptable?
为什么这是不可接受的?
document.getElementById('test').innerHTML += str
document.getElementById('test').innerHTML += str
would be the textbook way of doing it.
将是教科书的方式来做到这一点。
回答by Rafael Senne
This can solve
这个可以解决
document.getElementById("list-input-email").insertAdjacentHTML('beforeend', '<div class=""><input type="text" name="" value="" class="" /></div>');
回答by ?ukasz Szpak
InnerHTML clear all data like event for existing nodes
InnerHTML 清除现有节点的所有数据,如事件
append child with firstChild adds only first child to innerHTML. For example if we have to append:
append child with firstChild 只将第一个孩子添加到innerHTML。例如,如果我们必须附加:
<p>text1</p><p>text2</p>
only text1 will show up
只有 text1 会出现
What about this:
那这个呢:
adds special tag to innerHTML by append child and then edit outerHTML by deleting tag we've created. Don't know how smart it is but it works for me or you might change outerHTML to innerHTML so it doesn't have to use function replace
通过附加子元素将特殊标签添加到innerHTML,然后通过删除我们创建的标签来编辑outerHTML。不知道它有多聪明,但它对我有用,或者您可以将 outerHTML 更改为 innerHTML,因此它不必使用函数替换
function append(element, str)
{
var child = document.createElement('someshittyuniquetag');
child.innerHTML = str;
element.appendChild(child);
child.outerHTML = child.outerHTML.replace(/<\/?someshittyuniquetag>/, '');
// or Even child.outerHTML = child.innerHTML
}
<div id="testit">
This text is inside the div
<button onclick="append(document.getElementById('testit'), '<button>dadasasdas</button>')">To div</button>
<button onclick="append(this, 'some text')">to this</button>
</div>