title: Insert tag inside a specific range - algorithm for DOM tree modification
body: <p>I need an algorithm for manipulating DOM tree. </p>
  
  <p>For example I have this HTML code:</p>
  
  <pre><code>&lt;div&gt;
      This is 
      &lt;b&gt;interesting&lt;/b&gt; 
      &lt;a href="..."&gt;
          con
          &lt;i&gt;tent&lt;/i&gt;
      &lt;/a&gt;
      . It 
      &lt;i&gt;can be&lt;/i&gt; 
      edit by users
  &lt;/div&gt;
  </code></pre>
  
  <p>User selects text "<em>is interesting content. It can</em>" and presses a button on the website. An event <em>onClick</em> of the button calls a function <em>insertTag('u')</em>.</p>
  
  <p>After this the HTML code should look like this:</p>
  
  <pre><code>&lt;div&gt;
      This 
      &lt;u&gt;is 
          &lt;b&gt;interesting&lt;/b&gt; 
          &lt;a href="..."&gt;
              con
              &lt;i&gt;tent&lt;/i&gt;
          &lt;/a&gt;
          . It 
      &lt;/u&gt;
      &lt;i&gt;
          &lt;u&gt;can&lt;/u&gt;
          be
      &lt;/i&gt; 
      edit by users
  &lt;/div&gt;
  </code></pre>
  
  <p>What should <em>insertTag()</em> function do? I googled, but I didn't find any examples and algorithms for this problem.</p>