3

I am trying to do a search and replace of text that has the same name inside the body but it is partial working, some of the text is being replace, but then some of the old text still show up, not quite sure what is going on.

$(document).ready(function() {
    $('*').each(function(){
        if($(this).children().length == 0) 
            $(this).text($(this).text().replace("old text", "replace with new text"));
        });
});

much help is appreciated

thanks

Kevin
  • 85
  • 5

1 Answers1

5

Use the :contains pseudo-class selector to find any elements containing that text, then replace from there.

$(":contains('old text')").each(function(){
    $(this).text($(this).text().replace('old text', 'new text'));
});

If you know a list of elements that you'd like to target, another solution would be to first find those elements, then filter over them using :contains.

$('div, p, a, span').filter(":contains('old text')").each(function(){
    $(this).text($(this).text().replace('old text', 'new text'));
});
jaredhoyt
  • 1,565
  • 8
  • 7
  • @Roko - Thanks, but the examples are very different especially in terms of performance. The latter example would be able to take advantage of the native DOM querySelectorAll() method, then be able to search a smaller subset of elements for a given string. This would be faster, but not always practical. – jaredhoyt May 03 '12 at 23:40
  • @jaredhoyt thanks for the help jared, it is working, but it is case sensitive, is there a way to make this not case sensitive? I added the jquery expression for :contains, but still nothing – Kevin May 07 '12 at 15:18
  • @Kevin To make `:contains` case-insensitive, you'll have to extend the core selector. You should be able to find some examples online (e.g. [here](http://css-tricks.com/snippets/jquery/make-jquery-contains-case-insensitive/) and [here](http://stackoverflow.com/questions/187537/is-there-a-case-insensitive-jquery-contains-selector)). – jaredhoyt May 07 '12 at 15:24
  • @jaredhoyt hmm still nothing, still case sensitive, I think the .replace is making it case sensitive, I tried both of the examples that you posted – Kevin May 07 '12 at 16:48