title: Move html elements from container to container
body: <p>I've to divide a text into portions. Text contains only paragraphs ( p tags ) inside <code>&lt;div id="main"&gt;</code>. I wanted to insert some divs with id page1...pagen, and distribute the paragraphs  inside them.</p>
  
  <p>Here is my code, but it is not working properly. Divs are generated before the paragraphs, and the paragraphs aren`t moved inside them.</p>
  
  <p>Except the error, is there any more efficient way to do this?</p>
  
  <pre><code>    var n = 1;
      $('article').prepend('&lt;div id="pagecnt"&gt;&amp;nbsp&lt;/div&gt;&lt;br/&gt;');
  
      $('#pagecnt').append('&lt;a href="#'+n+'"&gt;'+n+'&lt;/a&gt;').after('&lt;div id="page'+n+'" style="display:block;"&gt;&lt;/div&gt;');
  
      var pargraph = $('p');
      for (var i = 0; i &lt; pargraph.length; i++)
      {
  
          if ( $(document).height() &lt; 2 * $(window).height() )
          {
              $('#page'+n).append(pargraph[i].detach());
          } else {
              $('#page'+n).after('&lt;div id="page' + ++n + '" style="display:none;"&gt;&lt;/div&gt;');
          }
      }
  </code></pre>
  
  <p>EDIT : this should be the result (basically)</p>
  
  <p><img src="https://i.stack.imgur.com/x91lE.png" alt="enter image description here"></p>