搜索并替换具有相同名称的所有文本实例

时间:2012-05-03 23:23:58

标签: jquery

我正在尝试搜索并替换正文中具有相同名称的文本 但它是部分工作,一些文本正在被替换,但后来一些旧文本仍然出现,不太确定发生了什么。

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

非常感谢

感谢

1 个答案:

答案 0 :(得分:5)

使用:contains伪类选择器查找包含该文本的任何元素,然后从那里替换。

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

如果您知道要定位的元素列表,则另一种解决方案是首先找到这些元素,然后使用:contains过滤它们。

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