112

Is there any way to change the value of a DOM textNode in web browser?

I specifically want to see if I can change the existing node, rather than creating a new one.

To clarify, I need to do this with Javascript. All text in the browser is stored in #textNodes which are children of other HTML nodes, but cannot have child nodes of their own.

As Ash answered below, content can be changed by setting the nodeValue property of these Objects.

Lampe2020
  • 115
  • 1
  • 12
levik
  • 114,835
  • 27
  • 73
  • 90
  • Example of HTML & what you would like to change? Do you want to do it using javascript? – shahkalpesh Mar 25 '09 at 06:31
  • 1
    During my research on same question, I found out that [Mozilla Developer Network raises a security notice about `innerHTML` usage, and favors `textContent` usage](https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML#Security_considerations). Using `textContent` works fine for me. – Joël Aug 22 '19 at 08:25

2 Answers2

163

If you have a specific node (of type #text) and want to change its value you can use the nodeValue property:

node.nodeValue="new value";

Note:

innerText (and possibly textContent) will return/set both the current node and all descendent nodes text, and so may not be the behaviour you want/expect.

Salman A
  • 262,204
  • 82
  • 430
  • 521
Ash
  • 60,973
  • 31
  • 151
  • 169
  • 3
    Yes, nodeValue is perfect for this. innerText and textContent differ in this regard: IE (who created innerText) doesn't support it on #text nodes (since there are no child nodes to textify), whereas textContent was meant to be used on both #Element AND #text nodes. – Crescent Fresh Mar 25 '09 at 07:39
  • 6
    There's also ‘data’ as a short synonym for ‘nodeValue’ on Text (as well as CDATASection and Comment). – bobince Mar 25 '09 at 15:39
  • 1
    nodeValue is the one I needed. For some reason I thought it was read-only, but seems to work on FF3 and IE7. Thanks! – levik Mar 25 '09 at 21:49
  • 8
    @petermeissner: This answers the question perfectly, so your downvote is completely unwarranted. – Tim Down Mar 29 '15 at 10:28
  • 2
    Works not always .. "When nodeValue is defined to be null, setting it has no effect." .. I opted in that case for "textContent" ... setting it updated also the value for "innerText" – foobored Nov 22 '17 at 17:24
  • 1
    Note that if you are trying to set the "text" of an element (and not a text node), you might have to `element.insertBefore(document.createTextNode('text'), null)` instead of `element.nodeValue='text'` if the node has no text children. – Christopher Schultz Jun 18 '20 at 00:05
  • 1
    This did not work for me, but `node.innerText = "new value"` did. – johannes Feb 23 '22 at 10:01
-15

I believe innerHTML is used for this... Then again, that isn't W3C approved... but it works...

node.innerHTML="new value";
petermeissner
  • 12,234
  • 5
  • 63
  • 63
KdgDev
  • 14,299
  • 46
  • 120
  • 156