对于此 HTML
<label id="nameWrapper"><input type="checkbox" name="name" />guest</label>
用其他文本替换 guest
的最短 JavaScript 代码是什么?我能想到的是,
$('#nameWrapper').contents().filter(function() {
return this.nodeType == 3;
}).replaceWith('other text');
最佳答案
非 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');
关于javascript - 替换具有非文本节点同级的文本节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4394457/