Daniel Lundahl Daniel Lundahl - 1 year ago 179
jQuery Question

jQuery if div contains this text, replace that part of the text

Like the title says, I want to replace a specific part of the text in a div.

The structure looks like this:

<div class="text_div">
This div contains some text.

And I want to replace only "contains" with "hello everyone", for example.
I can't find a solution for this.

Answer Source

You can use the text method and pass a function that returns the modified text, using the native String.prototype.replace method to perform the replacement:

​$(".text_div").text(function () {
    return $(this).text().replace("contains", "hello everyone"); 

Here's a working example.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download