更改文本节点文本

时间:2012-01-31 13:35:56

标签: javascript jquery html dom textnode

如何更改文本节点文本?

HTML:

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

我正在尝试将'aaa'和'bbb'更改为hello world。我成功地选择了这些节点,但无法更改其文本。

到目前为止Jquery:

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

JSFiddle

我可以用$textNodes来更改文字吗?

3 个答案:

答案 0 :(得分:3)

使用文本节点的nodeValuedata属性。两者都同样有效且得到很好的支持:

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

顺便说一句,IE&lt; 1&gt;中不存在Node.TEXT_NODE。 9,所以最好只使用3代替。

答案 1 :(得分:2)

您无法使用jQuery直接编辑文本节点。

直接在节点上使用原生datanodeValue属性。

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

jsFiddle

答案 2 :(得分:1)

MDN中花了很多时间后找到它:

由于某些愚蠢的原因,此属性称为nodeValue而不是value ...

修复了JQuery:

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

修正JSFiddle

相关问题