【问题标题】:replace a textnode that has non-textnode siblings替换具有非文本节点兄弟的文本节点
【发布时间】:2024-12-23 00:55:02
【问题描述】:

对于这个 HTML

客人

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

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

【问题讨论】:

    标签: javascript jquery


    【解决方案1】:

    非 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');
    

    【讨论】:

      最近更新 更多