3

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

Tom
  • 6,991
  • 13
  • 60
  • 78

4 Answers4

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.

Tomalak
  • 332,285
  • 67
  • 532
  • 628
2

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#

Peter
  • 14,221
  • 15
  • 70
  • 110
1
parent.innerText = text;
Tom
  • 6,991
  • 13
  • 60
  • 78
  • That's an alternative, of cause. I thought you were asking about text nodes specifically. – Tomalak May 05 '09 at 09:41
  • "I would like to change the text inside the parent" probably wasn't specific enough to say that I don't care how, I just want something very simple that will use the DOM to escape HTML. – Tom May 05 '09 at 10:32
0

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";
SridharKritha
  • 8,481
  • 2
  • 52
  • 43