Interactive
Interactive

Reputation: 1560

javascript replace text after the page has loaded

I want to remove/hide a piece of text that loads on my page.

The element doesn't have an id to relate to so I want to use a text-specific method.

Let's say the text is:"remove this line of text".
The html looks like this:

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

I have tried the following:

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

Didn't work. So I tried this:

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

Didn't work. The idea is that after the page is loaded it removes the line.
It doesn't produces any errors as well. Not even in the firebug.

Anyone?

Upvotes: 1

Views: 3706

Answers (2)

Pedro Lobito
Pedro Lobito

Reputation: 99001

I guess you can use find() and text(), i.e.:

$('.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>


Or simply:

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

Update:

After analyzing the link supplied on the comments, you can use the following:

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

Upvotes: 0

Rion Williams
Rion Williams

Reputation: 76577

Target Elements Based On Their Content

You could accomplish this using the :contains() pseudoselector in jQuery that would allow you to target certain elements based on their contents :

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

You can see a working example of this here.

Broader Approach (Just Targets Elements Based On Selectors)

If you wanted a more simply target it by a more general selector (i.e. any <strong> tags that appear beneath a class called aClassName :

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

You can see an example of this approach here.

Upvotes: 2

Related Questions