I am new to jquery, and I’m having trouble doing what I thought should be a very simple find and replace operation.
I want to change the text inside the the “<p>” tags. So for instance I might want to replace “your title” with “a title“.
<div id="ValidationSummary">
<ul>
<li>
<p>
Please specify your title</p>
</li>
<li>
<p>
Please enter your first name</p>
</li>
<li>
<p>
Please enter your surname</p>
</li>
</ul>
</div>
and here is the jQuery which isn’t doing anything:
$(function() {
$('#ValidationSummary').text().replace("your title", "a title");
$('#ValidationSummary').text().replace("first name", "christian name");
$('#ValidationSummary').text().replace("your surname", "your last name");
};
I really cannot see what I’m doing wrong, any ideas?
Please help, thanks
Any changes to strings in JS always produces a new string, rather than modifying what was there. Fortunately jQuery makes it easy to both retrieve and modify text at the same time:
Explanation:
returning a string from.text()tells jQuery to replace what was there (passed in asold) with this new string.Since
replace()returns a new string each time, we can chain multiple calls together, so that we only need one.text()call andreturnstatement.I used the selector
'#ValidationSummary p'since using.text()or.html()will replace the entire contents of the element it is operating on.