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:
$('#ValidationSummary p').text(function (i, old) {
return old
.replace('your title', 'a title')
.replace('first name', 'christian name')
.replace('your surname', 'your last name');
});
Explanation:
return
ing a string from .text()
tells jQuery to replace what was there (passed in as old
) 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 and return
statement.
I used the selector '#ValidationSummary p'
since using .text()
or .html()
will replace the entire contents of the element it is operating on.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With