From a DOM fragment coming from the user selected text window.getSelection()
:
<h1>Hello world!</h1>
<p>How <b>do y<i>o<i>u</b> do?</p>
I'd like to surround a <span class="foo"></span>
around each word, ie:
<h1><span class="foo">Hello</span> <span class="foo">world!</span></h1>
<p><span class="foo">How</span> <b><span class="foo">do</span> <span class="foo">y<i>o<i>u</span></b> <span class="foo">do?</span></p>
How can I do this in javascript?
For now here is what I have:
// Get highlighted text
var selection = window.getSelection();
// Iterate over ranges
for (var i = 0, l = selection.rangeCount; i < l; ++i) {(function () {
var range = selection.getRangeAt(i);
var fragment = range.cloneContents();
// HELP HERE: Surround each word in the fragment...
}())}