Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace word in <p> in <div> using jquery

I have a document with the following structure:

<div id="notice" class="box generalbox">
<p>
This is some text.
</p>
</div>

I want to replace the word "some" with the word "My" using jQuery.

How do i do this?

I tried:

$("#notice").text().replace("some", "My");

But that didnt work...

UPDATE: Thanks for all your replys. I used this solution to get this to work:

$("#notice p").text($("#notice p").text().replace("some", "My"));
like image 555
user2075124 Avatar asked Oct 11 '13 13:10

user2075124


1 Answers

You need to target the p tag inside the #notice:

$("#notice p").text(function(i, text) {
    return text.replace("some", "My");
});

Update 2020-03

This same logic can now be made even simpler by using an arrow function:

$('#notice p').text((i, t) => t.replace('some', 'My'));

This will work in any browser except Internet Explorer.

like image 174
Rory McCrossan Avatar answered Oct 03 '22 21:10

Rory McCrossan