2

How can I change text-nodes text?

HTML:

<p class='theClass'> bbb <a href=#> foo</a> aaa </p>

I'm trying to change 'aaa' and 'bbb' to hello world. I successed to select those nodes but couldn't change their text.

Jquery so far:

var $textNodes = $('.theClass').contents().filter(function() {
    return this.nodeType == Node.TEXT_NODE;
});

JSFiddle

What can I do with this $textNodes to change their text?

Community
  • 1
  • 1
gdoron
  • 147,333
  • 58
  • 291
  • 367

3 Answers3

4

Use the nodeValue or data property of the text node. Both are equally valid and well supported:

$textNodes.each(function() {
    this.data = "CHANGED";
});

Incidentally, Node.TEXT_NODE does not exist in IE < 9, so you'd be better off simply using 3 instead.

Tim Down
  • 318,141
  • 75
  • 454
  • 536
2

You can't directly edit a text node with jQuery.

Just use the native data or nodeValue property directly on the nodes.

$textNodes.each(function() {
    this.data = "Hello world";
 // this.nodeValue = "Hello world";
});

jsFiddle

gdoron
  • 147,333
  • 58
  • 291
  • 367
  • Thats weird, couldn't find `data` in [MDN](https://developer.mozilla.org/en/XUL/textnode) – gdoron Jan 31 '12 at 13:54
  • It's a standard DOM property. It's under the `CharacterData` interface in MDN: https://developer.mozilla.org/En/DOM/CharacterData – Tim Down Jan 31 '12 at 13:56
  • @gdoron: Have you ever checked out [quirksmode's compatibility tables](http://www.quirksmode.org/compatibility.html)? I learned quite a bit of the API just from there. –  Jan 31 '12 at 14:01
1

Found it after a lot of time in MDN:

This propery is called nodeValue not value for some stupid reason...

fixed JQuery:

var $textNodes = $('.theClass').contents().filter(function() {
    return this.nodeType == Node.TEXT_NODE;
}).each(function(){
    this.nodeValue = "hello World";
});

Fixed JSFiddle

gdoron
  • 147,333
  • 58
  • 291
  • 367
  • 1
    `nodeValue` is standard DOM property of `Node`s. `value` is a property of form controls that represents a different concept. – Tim Down Jan 31 '12 at 13:52