你如何替换不在特定div中的字符串?

Squ*_*rrl 6 javascript jquery replace

我有这个HTML:

<div id="content">This following word is not <span id="notOk">ok</span> but all the other words are ok</div>
Run Code Online (Sandbox Code Playgroud)

并利用这个jQuery我想要替换的单词okcool,只要这个词ok是不是里面跨度#notOk.

var content = $('#content').html()
content = content.replace('ok', 'cool');
$('#content').html(content)
Run Code Online (Sandbox Code Playgroud)

我也想保留句子而不是移动任何单词,这就是我尝试时发生的事情.我想我正在寻找类似dontGetElementByID('')的东西.?

小提琴

und*_*ned 6

您可以使用该.contents()方法并替换s的nodeValue属性textNode.

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

http://jsfiddle.net/82tmP/