Change text for text nodes

How to change the text of text nodes?

HTML:

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

I am trying to change "aaa" and "bbb" to hello world . I managed to select these nodes, but could not change their text.

JQuery:

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

Jsfiddle

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

+1
source share
3 answers

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

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

By the way, Node.TEXT_NODE does not exist in IE <9, so you'd better just use 3 instead.

+3
source

You cannot directly edit node text using jQuery.

Just use your own data or nodeValue directly on the nodes.

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

jsFiddle

+2
source

Found it after a lot of time in MDN :

This property 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

+1
source

Source: https://habr.com/ru/post/1398869/


All Articles