Change text-nodes text

我是研究僧i 提交于 2019-12-11 04:49:38

问题


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?


回答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.




回答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




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

Fixed JSFiddle



来源:https://stackoverflow.com/questions/9080407/change-text-nodes-text

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!