title: javascript: replace selected text from contenteditable on button click
body: <p>I have a div with contenteditable=true and a button for changing text div selected text onclick.</p>
  
  <p>Div editable:</p>
  
  <pre><code>&lt;div class="content" id="articleEditor" contenteditable="true"&gt;&lt;/div&gt;
  </code></pre>
  
  <p>Style Options</p>
  
  <pre><code>&lt;div class="editor-option"&gt;
      &lt;button id="changeText"&gt;change&lt;/button&gt;
  &lt;/div&gt;
  </code></pre>
  
  <p>Js file</p>
  
  <pre><code>function replaceSelectedText(replacementText){
      if (window.getSelection().rangeCount) {
          range = window.getSelection().getRangeAt(0);
          range.deleteContents();
          var el = document.createElement("span");
          el.innerHTML = replacementText;
          var frag = document.createDocumentFragment(), node, lastNode;
          while ( (node = el.firstChild) ) {
              lastNode = frag.appendChild(node);
          }
          range.insertNode(document.createTextNode(replacementText));
      }
  }
  
  $('button').click(function(){
      replaceSelectedText('&lt;span class="bold"&gt;'+window.getSelection().toString()+'&lt;/span&gt;');
  })
  </code></pre>
  
  <p>Now it works for all text selection except the last word. If I select the last word and then I click on the button, the selection is bold but everything I write after is bold too.</p>
  
  <p>How to fix this ?</p>