Mago99
Mago99

Reputation: 63

How to use replace in jQuery?

Can somebody tell me what is wrong with this code:

$("#replace").text().replace("cat","dog");

Upvotes: 0

Views: 2057

Answers (3)

Sadikhasan
Sadikhasan

Reputation: 18600

You can use replace function with jQuery object not on text.

$("#replace").text($("#replace").text().replace("cat","dog"));

Upvotes: 1

Milind Anantwar
Milind Anantwar

Reputation: 82241

Use callback function for .text():

function Type: Function( Integer index, String text ) => String A function returning the text content to set. Receives the index position of the element in the set and the old text value as arguments.

$("#replace").text(function(i,oldtext){
   return oldtext.replace("cat","dog");
})

Upvotes: 1

Tushar
Tushar

Reputation: 87203

You are not replacing the text of the element. You're just getting it and replacing the text but not updating the DOM.

$("#replace").text($('#replace').text().replace("cat","dog"));

OR

$("#replace").text(function() {
    return $(this).text().replace("cat", "dog");
});

Upvotes: 2

Related Questions