6

I have this html:

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

And using this jquery I'm trying to replace the word ok with cool, as long as the word ok is not inside the span #notOk.

var content = $('#content').html()
content = content.replace('ok', 'cool');
$('#content').html(content)

I also want to preserve the sentence and not move any words around, which is what happened when I tried. I guess I'm looking for something like dontGetElementByID('').?

FIDDLE

Squirrl
  • 4,909
  • 9
  • 47
  • 85
  • Not getting what you wanted to say. – Chirag Vidani Jan 27 '14 at 09:48
  • You mean to say that you want the word 'ok' gets replaced with 'cool' if its in span with Id=#notOk? And other 'ok' should not get replaced. Am I right? – Chirag Vidani Jan 27 '14 at 09:49
  • What do you want do?? change the first ok inside the span, the ok outside the span, or both? – user2891084 Jan 27 '14 at 09:49
  • After the replace I want the html to be `This following word is not ok but all the other words are cool` instead of `This following word is not cool but all the other words are ok` which is what is happening.. Is that clearer? – Squirrl Jan 27 '14 at 09:49
  • @user2891084 change the `ok` outside the span – Squirrl Jan 27 '14 at 09:51

2 Answers2

6

You can use the .contents() method and replace nodeValue properties of the textNodes.

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

http://jsfiddle.net/82tmP/

Ram
  • 143,282
  • 16
  • 168
  • 197
  • Very cool. And will this work if the #notOk span wraps different words and the replace method is called on those? It seems to. THanks : ) – Squirrl Jan 27 '14 at 09:55
  • http://jsfiddle.net/p8a7V/3/ Awesome http://www.w3schools.com/dom/dom_nodetype.asp Cool stuff – Squirrl Jan 27 '14 at 09:57
3

Replace the value just like you did.. then replace it back :)

var content = $('#content').html()
content = content.replace('ok', 'cool');
$('#content').html(content);

content = $('#notOk').html();
content = content.replace('cool', 'ok');
$('#notOk').html(content);
A1rPun
  • 16,287
  • 7
  • 57
  • 90