2010-12-09 77 views
1

对于该HTML替换具有非textnode兄弟姐妹

<标签 ID = “nameWrapper” > <输入 类型= “复选框” 名称= “名称” />旅客< /标记的textnode >

什么是用其他文本代替guest的最短javascript代码?我能想到的是,

$('#nameWrapper').contents().filter(function() { 
    return this.nodeType == 3; 
}).replaceWith('other text'); 

回答

2

非jQuery方法。

实施例:http://jsfiddle.net/patrick_dw/NLJ3e/

document.getElementById('nameWrapper').lastChild.data = 'new text'; 

或用jQuery选择缩短:

实施例:http://jsfiddle.net/patrick_dw/NLJ3e/1/

$('#nameWrapper')[0].lastChild.data = 'new text'; 

或者稍长(和慢),但更像jQuery:

实施例:http://jsfiddle.net/patrick_dw/NLJ3e/2/

$('#nameWrapper').contents().last().replaceWith('new text'); 
+0

1具有更好的解决方案:) – alex 2010-12-09 03:36:19