How to change the text of text nodes?
<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.
hello world
var $textNodes = $('.theClass').contents().filter(function() { return this.nodeType == Node.TEXT_NODE; });
Jsfiddle
What can I do with this $textNodes to change their text?
$textNodes
Use the nodeValue property or data of the node text. Both are equally important and well supported:
nodeValue
data
$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.
Node.TEXT_NODE
3
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
Found it after a lot of time in MDN :
This property is called nodeValue not value for some stupid reason ...
value
fixed jQuery:
var $textNodes = $('.theClass').contents().filter(function() { return this.nodeType == Node.TEXT_NODE; }).each(function(){ this.nodeValue = "hello World"; });
Fixed jsfiddle
Source: https://habr.com/ru/post/1398869/More articles:Writing Add List Function in OCaml - listGetting 401.2 when certificate authentication is enabled - certificateImages crashed when viewed in IE8 - javascriptGoogle Docs spreadsheet update - pythonHow to change text inside a range using jQuery, leaving the remaining intervals with content in it? - javascriptEnumeration and mapping with Scala 2.10 - scalaIs it possible to disable the IE Lync add-in using script - pluginsPrevent AppleScript script name change when changing passed arguments - osx-lionWhy does the browser request a cached file? - phpHow to create a method with an undefined number of parameters en C # - c #All Articles