Johnny
Johnny

Reputation: 1725

find and replace texts using jquery

I am trying to find and replace texts using jquery.

function replaceText() {
    var jthis = $(this);
    $("*").each(function() { 
        if(jthis.children().length==0) { 
            jthis.text(jthis.text().replace('nts:', 'nights:')); 
        } 
    });
}
$(document).ready(replaceText);
$("html").ajaxStop(replaceText);

here is my jsfiddle:

http://jsfiddle.net/2GENx

I need to replace the all "nts" texts on the page by "nights". Can you tell me why it's not working?

Upvotes: 0

Views: 711

Answers (1)

Ja͢ck
Ja͢ck

Reputation: 173532

I see that you have tried to avoid writing $(this) all the time by storing its value in jthis; the problem is that by doing so you effectively always inspect the same item.

Instead, save the reference inside the each() callback:

function replaceText() 
{
    jQuery("*").each(function() {
        var $this = jQuery(this);
        if ($this.children().length==0) { 
            $this.text($this.text().replace('nts:', 'nights:')); 
        } 
    });
}

It also seems that you're using jQuery next to something called wisdomweb on your page, and that doesn't support the .ajaxStop() feature; the only suggestions I can give you:

  1. hack the library to support .ajaxStop(),
  2. listen for dom changes and perform the replacement inside,
  3. use an even uglier setTimeout() option.

Upvotes: 1

Related Questions