Skip to content Skip to sidebar Skip to footer

Change Text-nodes Text

How can I change text-nodes text? HTML:

bbb foo aaa

I'm trying to change 'aaa' and 'bbb' to hello world. I success

Solution 1:

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.

Solution 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

Solution 3:

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() {
    returnthis.nodeType == Node.TEXT_NODE;
}).each(function(){
    this.nodeValue = "hello World";
});

Fixed JSFiddle

Post a Comment for "Change Text-nodes Text"