0

I have to following structure:

<div class='xx'>
  That is awesome!!
<a href="http://www.his-stuff.com">yodel</a>
</div>

<div class='xx'>
   can't touch this
</div>

Now I want to replace all occurrances of "is", no matter if they are standing alone or not. I made it that way:

$('.xx').each(function()
{
   $(this).html($(this).html().replace("is","was"));
});

I want the following results:

That is awesome -> That was awesome

Can't touch this -> Can't touch thwas

This works, but the url containing "is" is also modified

www.hwas-stuff.com

I do not want the url to be replaced but all others

Info: I cannot use text() instead of html() because the "real" code is a bit more complex (Inserts images instead of text)

Ole Albers
  • 8,715
  • 10
  • 73
  • 166

2 Answers2

1

Try this:

$('.xx').contents().filter(function() {
    return this.nodeType == Node.TEXT_NODE && this.nodeValue.trim() != '';
}).each(function() {
    this.nodeValue = this.nodeValue.replace('is','was');
});

Working demo

From a question I asked on Stack Overflow: https://stackoverflow.com/a/11167387/1420186

Community
  • 1
  • 1
Tony Dinh
  • 6,668
  • 5
  • 39
  • 58
  • Sadly I cannot use this to insert an image. It will display the source – Ole Albers Mar 22 '14 at 21:24
  • I'm sorry, but you just lost me here, i don't understand your need anymore. It's just not clear. – LostBalloon Mar 22 '14 at 21:27
  • Your solution directed me into the right direction. I had to do some modifications described there: http://stackoverflow.com/questions/7698673/add-html-to-text-node-extracted-via-node-nodevalue – Ole Albers Mar 22 '14 at 21:33
0

you could do this:

<div class='xx'>
    That is awesome!!
</div>
<a href="http://www.his-stuff.com">yodel</a>

or:

<div class='the-style'>
    <div class='xx'>
        That is awesome!!
    </div>
    <a href="http://www.his-stuff.com">yodel</a>
</div>

or:

<div class='foo bar'>
    <span class='is-was'>That is awesome!!</span>
    <a href="http://www.his-stuff.com">yodel</a>
</div>

I would prioritize fixing how you structured your html & your approach, rather than trying to find some funky way to patch the issue without really fixing it. Your future self will appreciate you more.

When creating classes, make sure they do a very specific (encapsulated) job and make the names descriptive, if you look at the twitter bootstrap library, it's an amazing example.

LostBalloon
  • 1,608
  • 3
  • 15
  • 31