[英]Appending HTML string to the DOM
How to append a HTML string such as如何 append 一个 HTML 字符串如
var str = '<p>Just some <span>text</span> here</p>';
to the <div>
with the id test
?到带有 id test
的<div>
?
(Btw div.innerHTML += str;
is not acceptable.) (顺便说一句div.innerHTML += str;
是不可接受的。)
Use insertAdjacentHTML
which is supported in all current browsers :使用所有当前浏览器都支持的insertAdjacentHTML
:
div.insertAdjacentHTML( 'beforeend', str );
The position parameter beforeend
will add inside the element, after its last child.位置参数beforeend
将添加到元素内部,在其最后一个子元素之后。
Live demo: http://jsfiddle.net/euQ5n/现场演示:http: //jsfiddle.net/euQ5n/
AppendChild
(E) is more than 2x faster than other solutions on chrome and safari, insertAdjacentHTML
(F) is fastest on firefox. AppendChild
(E) 在 chrome 和 safari 上比其他解决方案快 2 倍以上, insertAdjacentHTML
(F) 在 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. innerHTML=
(B)(不要与+=
(A) 混淆)是所有浏览器上的第二个快速解决方案,它比 E 和 F 更方便。
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)在 Chrome 75.0.3770(64 位)、Safari 11.1.0(13604.5.6)、Firefox 67.0.0(64 位)上设置环境 (2019.07.10) MacOs High Sierra 10.13.4
You can replay test in your machine here您可以在您的机器上重放测试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>
Is this acceptable?这可以接受吗?
var child = document.createElement('div');
child.innerHTML = str;
child = child.firstChild;
document.getElementById('test').appendChild(child);
But , Neil's answer is a better solution.但是,尼尔的答案是一个更好的解决方案。
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 字符串。
The right way is using insertAdjacentHTML
.正确的方法是使用insertAdjacentHTML
。 In Firefox earlier than 8, you can fall back to using Range.createContextualFragment
if your str
contains no script
tags.在 Firefox 8 之前的版本中,如果您的str
不包含script
标签,您可以回退到使用Range.createContextualFragment
。
If your str
contains script
tags, you need to remove script
elements from the fragment returned by createContextualFragment
before inserting the fragment.如果您的str
包含script
标签,则需要在插入片段之前从createContextualFragment
返回的片段中删除script
元素。 Otherwise, the scripts will run.否则,脚本将运行。 ( insertAdjacentHTML
marks scripts unexecutable.) ( insertAdjacentHTML
脚本标记为不可执行。)
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. 1:另存为 .html 文件并在 chrome 或 firefox 或 edge 中运行。 (IE wont work) (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 有两个必备条件:
But doesn't show console.log messages.但不显示 console.log 消息。 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.我只是想看看几行暂存代码的结果,其他的解决方案工作量太大。
这可以解决
document.getElementById("list-input-email").insertAdjacentHTML('beforeend', '<div class=""><input type="text" name="" value="" class="" /></div>');
InnerHTML clear all data like event for existing nodes InnerHTML 清除所有数据,例如现有节点的事件
append child with firstChild adds only first child to innerHTML. append child with firstChild 仅将第一个子元素添加到 innerHTML。 For example if we have to append:例如,如果我们必须附加:
<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.通过追加子元素将特殊标签添加到innerHTML,然后通过删除我们创建的标签来编辑outerHTML。 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不知道它有多聪明,但它对我有用,或者您可以将 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>
Why is that not acceptable?为什么这是不可接受的?
document.getElementById('test').innerHTML += str
would be the textbook way of doing it.将是教科书的做法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.