简体   繁体   中英

Change text-nodes text

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?

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM