Jquery: Find Text and replace

You can use .each() to loop through the <p> elements, and .text() to update the text.

For example:

$('#id1 p').each(function() {
    // get element text
    var text = $(this).text();
    // modify text
    text = text.replace('dog', 'doll');
    // update element text
    $(this).text(text); 
});

Demo: https://jsfiddle.net/8gra4xjw/


[Updated to reflect comments]

Note: The above replaces the first occurrence of ‘dog’ only. To replace all occurrences, you could use:

// modify text (replace all)
text = text.replace(/dog/g, 'doll');

See also: How to replace all occurrences of a string in JavaScript


If the new text must contain HTML entities like &nbsp;, you could use:

// update element text (html)
$(this).html(text);

See also: What is the difference between jQuery: text() and html() ?

Leave a Comment