Replace selected text in Firefox
<p>How can I replace the selected text with another text using PURE javascript, in Firefox?</p>

<p>This I use to get the selection:</p>

<pre><code>var sel = this.getSelection();
var range = sel.getRangeAt(0);
</code></pre>

<p><strong>And also this important issue:</strong><br>
I want to keep the original format of characters (of course the new string will have the right format )<br>
The selection can be done "cross-elements" (by this I mean that the selection can contain some text from one element like div or table and some text from another elements).  </p>

<p>example, the document:</p>

<pre><code>&lt;div&gt;
 this is a test
&lt;/div&gt;
&lt;div&gt;
&lt;b&gt;still a test&lt;/b&gt;
&lt;/div&gt;
 &lt;table style="width:100%;"&gt;
        &lt;tr&gt;
            &lt;td&gt;
                another word&lt;/td&gt;
            &lt;td&gt;
                stackoverflow&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
            &lt;td&gt;
                bump&lt;/td&gt;
            &lt;td&gt;
               &lt;/td&gt;
        &lt;/tr&gt;
    &lt;/table&gt;
</code></pre>

<p>the user select the following text (via one selection):</p>

<blockquote>
  <p>his is a test still a test anot</p>
</blockquote>

<p>So now I want to replace the text keeping the format, for instance replace every thing with new string =</p>

<blockquote>
  <p>XXX XX X XXXX XXXXX X XXXX XXXX</p>
</blockquote>

<p>Final document (after replace) will be:</p>

<pre><code>&lt;div&gt;
 tXXX XX X XXXX
&lt;/div&gt;
&lt;div&gt;
&lt;b&gt;XXXXX X XXXX&lt;/b&gt;
&lt;/div&gt;
 &lt;table style="width:100%;"&gt;
        &lt;tr&gt;
            &lt;td&gt;
                XXXXher word&lt;/td&gt;
            &lt;td&gt;
                stackoverflow&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
            &lt;td&gt;
                bump&lt;/td&gt;
            &lt;td&gt;
               &lt;/td&gt;
        &lt;/tr&gt;
    &lt;/table&gt;
</code></pre>
