0

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...

}())}
abernier
  • 27,030
  • 20
  • 83
  • 114
  • please post your javascript too – Ejaz May 10 '14 at 20:42
  • You can use .split(' ') http://stackoverflow.com/questions/4514323/javascript-equivalent-to-php-explode – Max May 10 '14 at 20:43
  • The answer to [this](http://stackoverflow.com/questions/11171865/window-getselection-getrangeat-not-working-properly) question has a fragment of Javascript that may help. – Joel Allison May 10 '14 at 22:55

0 Answers0