JavaScript TextNode 更新

发布于 2024-07-18 14:13:50 字数 460 浏览 4 评论 0原文

如果我有一个

var t = document.createTextNode(text)
parent.appendChild(t);

是否可以简单地更新t的内容?

我想在不使用 removeChildcreateTextNodeappendChild 的情况下更改 parent 内的文本。 为什么我需要这个而不是仅仅使用 innerHTML ? 因为我不想用 HTML 代码更新元素的内容,并且 text 可能包含特殊字符,例如 text 。 或& 它应该由 TextNode 的 DOM 方法解析。

谢谢,
汤姆

If I have a

var t = document.createTextNode(text)
parent.appendChild(t);

Is it possible to simply update the contents of t?

I would like to change the text inside the parent without using removeChild, createTextNode and appendChild. Why would I need this instead of just using innerHTML? Because I don't want to update the contents of the element with HTML code and the text may contain special characters, such as < or & which should be parsed by TextNode's DOM methods.

Thanks,
Tom

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

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

发布评论

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

评论(4

埋情葬爱 2024-07-25 14:13:50

请注意,相邻的文本节点会合并为一个(因为实际上没有办法区分两个相邻的文本节点)。

文本节点的内容可以使用其 nodeValue 属性进行更新(请参阅 MDC)。

由于文本节点的定义不能包含任何标记,因此没有 innerHTML 属性。

Be aware that adjacent text nodes are collapsed into one (since there is really no way to distinguish two adjacent text nodes).

The contents of a text node can be updated using it's nodeValue property (see MDC).

Since a text node by it's very definition cannot contain any markup, there is no innerHTML property.

一杆小烟枪 2024-07-25 14:13:50

如果保留 TextNode 对象的实例(示例代码中的 t ),那么您可以使用各种函数(如 ReplaceData()、substringData() 等)更改内容。

请参阅此页面以获得很好的参考:
http://msdn.microsoft.com/en-我们/库/ms535905(VS.85).aspx#

If you keep the instance of the TextNode object (t in your example code) then you can change the content using various functions like replaceData(), substringData(), etc..

See this page for a nice reference:
http://msdn.microsoft.com/en-us/library/ms535905(VS.85).aspx#

梓梦 2024-07-25 14:13:50
parent.innerText = text;
parent.innerText = text;
恍梦境° 2024-07-25 14:13:50

下面的示例代码用“新值”覆盖文本节点的“旧值”。

const textNode = document.createTextNode("Old Value");
parent.appendChild(textNode);

textNode.nodeValue = "New Value";

Below example code overwrites the "Old Value" of the text node with the "New Value".

const textNode = document.createTextNode("Old Value");
parent.appendChild(textNode);

textNode.nodeValue = "New Value";
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文