Reputation: 63
Can somebody tell me what is wrong with this code:
$("#replace").text().replace("cat","dog");
Upvotes: 0
Views: 2057
Reputation: 18600
You can use replace function with jQuery object not on text.
$("#replace").text($("#replace").text().replace("cat","dog"));
Upvotes: 1
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
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