Search and replace all instances of text with the same name

I try to search and replace text with the same name inside the body but it partially works, some of the text is replaced, but then some of the old text still appears, not quite sure what is happening.

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

a lot of help is appreciated

thank

+3
source share
1 answer

Use the pseudo-class selector :containsto find any elements containing this text, then replace it.

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

If you know the list of elements you want to target, another solution would be to first find these elements and then filter them using: contains.

$('div, p, a, span').filter(":contains('old text')").each(function(){
    $(this).text($(this).text().replace('old text', 'new text'));
});
+5
source

All Articles