Replacing text with jQuery
Use jQuery to select the first instance of a string of text and replace it with something else.
by Jon Fuller
HTML
<div class="wrapper">
<h1>My Introduction</h1>
<p>Well hello there, how's it going? Pretty good, I hope!</p>
<a href="#0">Yep!!!</a>
</div>
<hr>
<div>
Above, "Introduction" was replaced with "Awesome Introduction".<br>
Then, "hello" was replaced with "hey".<br>
Finally, the link's FIRST eclamation point was replaced with a question mark... since this will only replace the first instance within the selector.
</div>
JavaScript
// replaces only the text mentioned... and only the first instance within selector
jQuery(function($){
$('.wrapper h1:first-child').text(function () {
return $(this).text().replace('Introduction', 'Awesome Introduction');
});
$('.wrapper p').text(function () {
return $(this).text().replace('hello', 'hey');
});
$('.wrapper a[href^="#0"]').text(function () {
return $(this).text().replace('!', '?');
});
});