将 HTML 字符串附加到 DOM

发布于 2024-12-03 19:01:19 字数 256 浏览 0 评论 0 原文

如何

var str = '<p>Just some <span>text</span> here</p>';

使用 id test 附加 HTML 字符串(例如

)?

(顺便说一句 div.innerHTML += str; 是不可接受的。)

How to append a HTML string such as

var str = '<p>Just some <span>text</span> here</p>';

to the <div> with the id test?

(Btw div.innerHTML += str; is not acceptable.)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(11

耳根太软 2024-12-10 19:01:19

使用 insertAdjacentHTML ,其中 <所有当前版本都支持 href="https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTML#browser_compatibility" rel="noreferrer"> browsers:

div.insertAdjacentHTML( 'beforeend', str );

位置参数 beforeend 将添加到元素内部,位于其最后一个子元素之后。

现场演示: http://jsfiddle.net/euQ5n/

Use insertAdjacentHTML which is supported in all current browsers:

div.insertAdjacentHTML( 'beforeend', str );

The position parameter beforeend will add inside the element, after its last child.

Live demo: http://jsfiddle.net/euQ5n/

终陌 2024-12-10 19:01:19

性能

AppendChild (E) 比 Chrome 和 safari 上的其他解决方案快 2 倍以上,insertAdjacentHTML(F) 在 Firefox 上速度最快。 innerHTML= (B)(不要与 += (A) 混淆)是所有浏览器上第二快的解决方案,它比 E 和 F 方便得多。

详细信息

设置环境 (2019.07.10) Chrome 75.0.3770(64 位)、Safari 11.1.0 上的 MacOs High Sierra 10.13.4 (13604.5.6)、Firefox 67.0.0(64 位)

在此处输入图像描述

  • Chrome E(每秒 140k 操作)速度最快,B (47k) 和 F (46k) 最快第二,A (332) 在 Firefox 上最慢
  • F (94k) 最快,然后 B(80k)、D (73k)、E(64k)、C (21k) 最慢是
  • Safari 上 A(466) E(207k) 是最快,然后是 B(89k)、F(88k)、D(83k)、C (25k),最慢的是 A(509)

您可以在以下位置重放测试您的机器此处

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>

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.

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)

enter image description here

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

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>

陈甜 2024-12-10 19:01:19

这是可以接受的吗?

var child = document.createElement('div');
child.innerHTML = str;
child = child.firstChild;
document.getElementById('test').appendChild(child);

jsFiddle

但是尼尔的答案是一个更好的解决方案。

Is this acceptable?

var child = document.createElement('div');
child.innerHTML = str;
child = child.firstChild;
document.getElementById('test').appendChild(child);

jsFiddle.

But, Neil's answer is a better solution.

走野 2024-12-10 19:01:19

这个想法是在中间元素上使用 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);
}

这可以避免清除 div#test 上的任何事件处理程序,但仍然允许您附加 HTML 字符串。

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.

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.

双马尾 2024-12-10 19:01:19

正确的方法是使用 insertAdjacentHTML。在 Firefox 8 之前的版本中,如果您的 str 不包含 script 标签,您可以回退到使用 Range.createContextualFragment

如果您的 str 包含 script 标签,则需要先从 createContextualFragment 返回的片段中删除 script 元素,然后再插入分段。否则,脚本将运行。 (insertAdjacentHTML 将脚本标记为不可执行。)

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.

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

素染倾城色 2024-12-10 19:01:19

快速破解


<script>
document.children[0].innerHTML="<h1>QUICK_HACK</h1>";
</script>

用例

1:另存为.html文件并在chrome或firefox或edge中运行。 (IE 无法工作)

2:在 http://js.do 中使用

实际操作:
http://js.do/HeavyMetalCookies/quick_hack

细分评论:

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

我发布的原因:

JS.do 有两个必须具备的功能:

  1. 没有自动完成
  2. 功能 垂直监视器友好

但不显示 console.log 消息。
来到这里寻找快速解决方案。
我只想看看结果
几行暂存器代码,
其他解决方案的工作量太大。

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)

2: Use in http://js.do

In Action:
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:

  1. No autocomplete
  2. 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.

风渺 2024-12-10 19:01:19

这可以解决

 document.getElementById("list-input-email").insertAdjacentHTML('beforeend', '<div class=""><input type="text" name="" value="" class="" /></div>');

This can solve

 document.getElementById("list-input-email").insertAdjacentHTML('beforeend', '<div class=""><input type="text" name="" value="" class="" /></div>');
枯寂 2024-12-10 19:01:19

InnerHTML 清除所有数据,例如现有节点的事件,

将子项附加到firstChild 仅将第一个子项添加到innerHTML。例如,如果我们必须附加:

 <p>text1</p><p>text2</p>

仅显示 text1

怎么样:

通过附加子项将特殊标记添加到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>

InnerHTML clear all data like event for existing nodes

append child with firstChild adds only first child to innerHTML. For example if we have to append:

 <p>text1</p><p>text2</p>

only text1 will show up

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

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>

伴随着你 2024-12-10 19:01:19

为什么这是不可接受的?

document.getElementById('test').innerHTML += str

将是教科书上执行此操作的方法。

Why is that not acceptable?

document.getElementById('test').innerHTML += str

would be the textbook way of doing it.

风铃鹿 2024-12-10 19:01:19

最短 - 18 个字符(不要将 += (OP 提及)与 = 更多详细信息此处

test.innerHTML=str

var str = '<p>Just some <span>text</span> here</p>';

test.innerHTML=str
<div id="test"></div>

Shortest - 18 chars (not confuse += (mention by OP) with = more details here)

test.innerHTML=str

var str = '<p>Just some <span>text</span> here</p>';

test.innerHTML=str
<div id="test"></div>

一梦等七年七年为一梦 2024-12-10 19:01:19

我的问题的答案就是这样;一个带有空值的简单 Map;我所能得到的只是一个非常沉重且不精确的答案。我想知道谁结束了我的问题...甚至懒得阅读

"use strict"
try {
    const fruits = new Map([["Banana",""],["Apples", ""], ["Orange"," "]]);
    
    let text = "<h1>Fruits</h1>" + "<ul>";
    
    fruits.forEach(function(value, key){
       text += "<li>" + key + value + "<br>" + "</li>"
    });
    
    text +="</li> ";
    
    document.getElementById('demo').innerHTML = text;
} catch(err){
    document.getElementById('theError').innerHTML = err;
}

The answer to my Question was just this; a simple Map with an empty value; and all I can get is a very heavy answer and not precise. I wonder who closed my question... didn't even bother to read

"use strict"
try {
    const fruits = new Map([["Banana",""],["Apples", ""], ["Orange"," "]]);
    
    let text = "<h1>Fruits</h1>" + "<ul>";
    
    fruits.forEach(function(value, key){
       text += "<li>" + key + value + "<br>" + "</li>"
    });
    
    text +="</li> ";
    
    document.getElementById('demo').innerHTML = text;
} catch(err){
    document.getElementById('theError').innerHTML = err;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文