12

I'm playing around with finding and replacing text.

The only problem I'm having is finding a text string, that is not attached to an element with an ID. Otherwise, it would be easy.

I'm trying something like this:

$("*").each(function () {
    $(this).html(this.html().replace('Original Text','New Text'));
});

Not working too well.
Anyone run into this before?

Also, if I have several words or phrases to find and replace, how does that affect the speed/processing power of the user's browser? Is it a memory hog?

Gumbo
  • 643,351
  • 109
  • 780
  • 844
coffeemonitor
  • 12,780
  • 34
  • 99
  • 149

5 Answers5

21
$("*").contents().each(function() {
    if(this.nodeType == 3)
        this.nodeValue = this.nodeValue.replace("old", "new");
});
user187291
  • 53,363
  • 19
  • 95
  • 127
6

Takpar, your code works too. It seems to stop a few other things from working, but only items I'm pulling dynamically. For example, when I'm using .ajax(). Not sure why, but that's why I ran into. I'll test more.

On a related topic, Gumbo's code works:

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

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.

Is a limit I have to live with?

JellyBelly
  • 2,451
  • 2
  • 21
  • 41
coffeemonitor
  • 12,780
  • 34
  • 99
  • 149
  • this works well in modern browsers I passed this through JS Lint and it said you were missing one `=` equal sign, so i added it. How can i make this compatible with IE8 -IE7 ? @coffeemonitor @jellybelly – breezy Nov 02 '12 at 20:30
4

why don't you simply use:

$('body').html($('body').html().replace('Original Text','New Text'));
Alexar
  • 1,858
  • 5
  • 24
  • 34
1

You want the :contains() selector. http://api.jquery.com/contains-selector/

$("*:contains('Original Text')").each(...);
  • 1
    `:contains` is not a good idea: “The matching text can appear directly within the selected element, *in any of that element's descendants, or a combination thereof*.” – Gumbo Feb 27 '10 at 22:36
  • Only true if you don't want to replace it in descendants. –  Feb 27 '10 at 22:51
  • Meaning, the replace method is going to do the replacing, not the selector. –  Feb 27 '10 at 22:55
0
$("*").each(function () { 
if ($(this).children().length == 0){ 
     $(this).html($(this).html().replace(/Old String/g, "New String"));
}});