0

Can somebody tell me what is wrong with this code:

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

3 Answers 3

2

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");
});
Sign up to request clarification or add additional context in comments.

Comments

1

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");
})

Comments

1

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.