最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

dom - JavaScript TextNode update - Stack Overflow

programmeradmin10浏览0评论

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

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

Share Improve this question asked May 5, 2009 at 9:08 TomTom 7,22315 gold badges64 silver badges79 bronze badges 2
  • Do you want to display actual HTML or really just plain text? – Tomalak Commented May 5, 2009 at 9:15
  • I want to change the text inside parent and make it appear as plain text (ie, have the DOM replace < with &lt;). – Tom Commented May 5, 2009 at 9:26
Add a comment  | 

4 Answers 4

Reset to default 11

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.

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#

parent.innerText = text;

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";
发布评论

评论列表(0)

  1. 暂无评论