为什么没有 document.createHTMLNode() ?
我想在当前范围(W3C 范围)插入 html。
我想我必须使用 insertNode 方法。它与文本配合得很好。
示例:
var node = document.createTextNode("some text");
range.insertNode(node);
问题是我想插入 html(可能类似于“
测试
更多文本”)。并且没有createHTMLNode()。我尝试使用createElement('div'),给它一个id,将html作为innerHTML,然后尝试在插入后用它的nodeValue替换它,但它给了我DOM错误。
有没有一种方法可以做到这一点,而无需在我想要插入的 html 周围添加额外的 html 元素?
I want to insert html at the current range (a W3C Range).
I guess i have to use the method insertNode. And it works great with text.
Example:
var node = document.createTextNode("some text");
range.insertNode(node);
The problem is that i want to insert html (might be something like "<h1>test</h1>some more text"). And there is no createHTMLNode().
I've tried to use createElement('div'), give it an id, and the html as innerHTML and then trying to replace it with it's nodeValue after inserting it but it gives me DOM Errors.
Is there a way to do this without getting an extra html-element around the html i want to insert?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
因为
"
test
some more text"
由一个 HTML 元素和两段文本组成。它不是节点。如果您想插入 HTML,请使用
innerHTML
。创建一个元素(不要将其添加到文档中)。设置其innerHTML。然后通过循环 foo.childNodes 来移动其所有子节点。
Because
"<h1>test</h1>some more text"
consists of an HTML element and two pieces of text. It isn't a node.If you want to insert HTML then use
innerHTML
.Create an element (don't add it to the document). Set its innerHTML. Then move all its child nodes by looping over
foo.childNodes
.在某些浏览器(尤其是任何版本的 IE)中,
Range
对象最初具有非标准的createContextualFragment()
可能会有所帮助。未来版本的浏览器(例如 IE)很可能会实现这一点,因为这是一个例子:
In some browsers (notably not any version of IE),
Range
objects have an originally non-standardcreateContextualFragment()
that may help. It's likely that future versions of browsers such as IE will implement this now that it has been standardized.Here's an example:
尝试
来自:http://www.koders.com/javascript/fid21CDC3EB9772B0A50EA149866133F0269A1D37FA.aspx
Try
From: http://www.koders.com/javascript/fid21CDC3EB9772B0A50EA149866133F0269A1D37FA.aspx
Range.insertNode() 方法在 Range 的开头插入一个节点。
资源
https://developer. mozilla.org/en-US/docs/Web/API/range/insertNode
The Range.insertNode() method inserts a node at the start of the Range.
Resources
https://developer.mozilla.org/en-US/docs/Web/API/range/insertNode
不用innerHTML,只需使用appendChild(element);
这可能对您有帮助。。如果你想在这里发表评论,我会给你一个例子
Instead of innerHTML just use appendChild(element);
this may help you..If you want comment here, and I will give you an example