gpt4 book ai didi

javascript - javascript中的CreateTextNode附加html内容

转载 作者:行者123 更新时间:2023-12-01 02:43:05 25 4
gpt4 key购买 nike

我正在尝试使用附加子项将 html 格式的 block 附加到现有的 div 中。但我看到附加的是 html 代码而不是格式化的 html。有关如何使用appendChild 和createTextNode 添加html 设计而不是html 代码的任何指示吗?

Fiddle

<div id="currentElement">
<div>
<h2>
Hello test
</h2>
</div>
</div>

脚本

var ele = document.getElementById("currentElement");
var newHtml = "<div><h3>hello test continued</h3></div>";
ele.appendChild(document.createTextNode(newHtml));

最佳答案

为什么不直接使用 Element.innerHTML ?您可以使用 ele.innerHTML = newHtml 覆盖内容,或使用 ele.innerHTML += newHtml 添加到现有内容。

var ele = document.getElementById("currentElement");
var newHtml = "<div><h3>hello test continued</h3></div>";
ele.innerHTML += newHtml;
<div id="currentElement">
<div>
<h2>
Hello test
</h2>
</div>
</div>

请注意,这将删除任何现有的事件处理程序。为了保留处理程序,您应该使用 Element.insertAdjacentHTML() 相反:

var ele = document.getElementById("currentElement");
var newHtml = "<div><h3>hello test continued</h3></div>";
ele.insertAdjacentHTML('beforeend', newHtml);
<div id="currentElement">
<div>
<h2>
Hello test
</h2>
</div>
</div>

请注意,.insertAdjacentHTML() 提供了选择插入文本的位置的功能,其中应使用以下其中一个作为(强制)第一个函数参数: p>

  • beforebegin:在元素本身之前。
  • afterbegin:就在元素内部,在其第一个子元素之前。
  • beforeend:就在元素内部,在其最后一个子元素之后。
  • afterend:在元素本身之后。

在上面的示例中我使用了 beforeend

希望这有帮助! :)

关于javascript - javascript中的CreateTextNode附加html内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47425224/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com