JavaScript 在页面加载后替换文本

javascript replace text after the page has loaded

本文关键字:替换 文本 加载 JavaScript      更新时间:2023-09-26

我想删除/隐藏加载到我的页面上的一段文本。

该元素没有与之相关的 id,因此我想使用特定于文本的方法。

假设文本是:"删除此行文本"。
网页如下所示:

<div class="aClassName">
<p>
    <strong>remove this line of text</strong>
    ... the rest of the content.
</p>

我尝试了以下方法:

jQuery(document).ready(function($){
    document.body.innerHTML = document.body.innerHTML.replace('remove this line of text', '');
});

没用。所以我试了这个:

jQuery(document).ready(function($){
    $("body").children().each(function () {
       $(this).html( $(this).html().replace(/remove this line of text/g,"") );
    });
});

没用。这个想法是,在加载页面后,它会删除该行。
它也不会产生任何错误。甚至在萤火虫中也没有。

任何人?

根据元素的内容确定目标元素

您可以使用 jQuery 中的 :contains() 伪选择器来实现这一点,该伪选择器允许您根据某些元素的内容来定位它们:

$(function(){
   // This will remove any strong elements that contain "remove this line of text"
   $('strong:contains("remove this line of text")').remove();
});

您可以在此处看到一个工作示例。

更广泛的方法(仅基于选择器定位元素(

如果你想要一个更通用的选择器(即出现在名为aClassName的类下的任何<strong>标签(来定位它:

$('.aClassName strong').remove();

您可以在此处查看此方法的示例。

我想你可以使用 find(( 和 text((,即:

$('.aClassName').find('strong').text("123");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="aClassName">
<p>
    <strong>remove this line of text</strong>
    ... the rest of the content.
</p>


或者简单地说:

$('strong:contains("remove this line of text")').text("New text");

更新:

分析评论中提供的链接后,您可以使用以下内容:

$('.payment_method_mollie_wc_gateway_ideal').find('strong').text("");