Consider this document fragment:
<div id="test">
<h1>An article about John</h1>
<p>The frist paragraph is about John.</p>
<p>The second paragraph contains a <a href="#">link to John's CV</a>.</p>
<div class="comments">
<h2>Comments to John's article</h2>
<ul>
<li>Some user asks John a question.</li>
<li>John responds.</li>
</ul>
</div>
</div>
I would like to replace every occurrence of the string "John" with the string "Peter". This could be done via HTML rewriting:
$('#test').html(function(i, v) {
return v.replace(/John/g, 'Peter');
});
Working demo: http://jsfiddle.net/v2yp5/
The above jQuery code looks simple and straight-forward, but this is deceiving because it is a lousy solution. HTML rewriting recreates all the DOM nodes inside the #test DIV. Subsequently, changes made on that DOM subtree programmatically (for instance "onevent"
handlers), or by the user (entered form fields) are not preserved.
So what would be an appropriate way to perform this task?