views:

691

answers:

2

I received some amazing help from others, concerning finding and replacing text with jquery.

The code below will find the word: "Subject:" and replace it with "Name:"

$("*").each(function () { 
   if ($(this).children().length == 0) { 
      $(this).text($(this).text().replace('Subject:','Name:')); 
   } 
});

And this works wonderfully.

The only thing I'm running into issues with is replacing text that is loaded after the page loads.

I do have some javascript functions that are displaying data from the server, but only after the page has loaded all elements. For example, a user selects a value from a dropdown that initiates an event to load a list of products from the database.

I format some of those products like this:

Granny Smith Apples Price: x.xx per pound Nutritional facts....

I will only want to find a replace the word "Price:", and possibly replace it with "Cost:".

But as I mentioned, that data has not been loaded yet. And only displays after the user selects "Granny Smith Apples" from the dropdown menu.

Is this a limit I have to live with?

+1  A: 

Call your function from the $(document).ready() callback like this

$(document).ready(function() { replace_stuff(); } );
Otto Allmendinger
I'm already doing that, and still not affecting data loaded after the page has been loaded.
+1  A: 

You could try attaching an event to the ajaxStop event as well as on load:

function replaceText() {
    $("*").each(function() { 
        if($(this).children().length==0) { 
            $(this).text($(this).text().replace('Subject:', 'Name:')); 
        } 
    });
}
$(document).ready(replaceText);
$("html").ajaxStop(replaceText);
icktoofay
That works! Good idea, and yet so simple.Thank you!
Why create so many jq objects....cache $(this) refs instead
redsquare
redsquare: If you didn't notice, the person that asked the question used multiple `$(this)` expressions also. I just was informing them about the `ajaxStop` event, not the correct way to refer to `$(this)`.
icktoofay