JavaScript中的CreateTextNode附加html内容 [英] CreateTextNode in javascript appends html content
问题描述
我正在尝试使用append child将html格式的块附加到现有的div中.但是我看到html代码是附加的,而不是格式化的html.关于如何使用appendChild和createTextNode添加html设计而不是html代码的任何指针?
< div id ="currentElement">< div>< h2>你好测试</h2></div></div>
脚本
var ele = document.getElementById("currentElement");var newHtml =< div< h3> hello测试继续</h3</div>";ele.appendChild(document.createTextNode(newHtml));
var ele = document.getElementById("currentElement");var newHtml =< div< h3> hello测试继续</h3</div>";ele.innerHTML + = newHtml;
< div id ="currentElement">< div>< h2>你好测试</h2></div></div>
请注意,这将删除所有现有的事件处理程序.为了保留处理程序,您应使用 Element.insertAdjacentHTML()
:
var ele = document.getElementById("currentElement");var newHtml =< div< h3> hello测试继续</h3</div>";ele.insertAdjacentHTML('beforeend',newHtml);
< div id ="currentElement">< div>< h2>你好测试</h2></div></div>
请注意, .insertAdjacentHTML()
提供了选择 where 的功能,其中插入的文本应与以下(强制性的)第一个函数参数之一一起使用:>
-
before-begin
:在元素本身之前. -
之后开始
:就在元素内部,在其第一个子元素之前. -
beforeend
:就在元素内,在其最后一个子元素之后. -
afterend
:在元素本身之后.
在上面的示例中,我已经使用了 beforeend
.
希望这会有所帮助!:)
I am trying to append html formatted block to a existing div using append child. But I see the html code is appending instead of formatted html. Any pointer on how to add html design instead of html code with appendChild and createTextNode?
<div id="currentElement">
<div>
<h2>
Hello test
</h2>
</div>
</div>
Script
var ele = document.getElementById("currentElement");
var newHtml = "<div><h3>hello test continued</h3></div>";
ele.appendChild(document.createTextNode(newHtml));
Why not just use Element.innerHTML
? You can use ele.innerHTML = newHtml
to overwrite the content, or ele.innerHTML += newHtml
to add to the existing content.
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>
Note that this will remove any existing event handlers. In order to retain handlers, you should use Element.insertAdjacentHTML()
instead:
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>
Note that .insertAdjacentHTML()
provides the ability to choose where the inserted text should go with one of the following as the (mandatory) first function parameter:
beforebegin
: Before the element itself.afterbegin
: Just inside the element, before its first child.beforeend
: Just inside the element, after its last child.afterend
: After the element itself.
I've gone with beforeend
in the above example.
Hope this helps! :)
这篇关于JavaScript中的CreateTextNode附加html内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!