我有这个HTML:

<div id="content">This following word is not <span id="notOk">ok</span> but all the other words are ok</div>

并且使用此jquery,我尝试将ok替换为cool,只要单词ok不在span #notOk内。
var content = $('#content').html()
content = content.replace('ok', 'cool');
$('#content').html(content)

我还想保留句子,不要四处移动,这是我尝试时发生的情况。我想我正在寻找类似dontGetElementByID('')的东西。

FIDDLE

最佳答案

您可以使用.contents()方法并替换nodeValuetextNode属性。

$('#content').contents().each(function(){
    if (this.nodeType === 3)
        this.nodeValue = this.nodeValue.replace('ok', 'cool');
});

http://jsfiddle.net/82tmP/

关于javascript - 如何替换不在特定div内的字符串?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21377482/

10-12 12:21
查看更多