jQuery bug when trying to insert partial elements before() / after()?
<p>I'm trying to wrap a div around an element (my 'template' div) by using jQuery's before() and after().  When I try to insert a closing  after the selected element, it actually gets placed before the target.</p>

<p><strong>Example:</strong></p>

<pre><code>&lt;!DOCTYPE html&gt;
&lt;html lang="en"&gt;
&lt;head&gt;
&lt;meta charset="UTF-8" /&gt;
&lt;title&gt;Div Wrap&lt;/title&gt;

&lt;script src="http://code.jquery.com/jquery-1.4.4.min.js"&gt;&lt;/script&gt;

&lt;script&gt;
$('document').ready(function() {
    var beforestr = "&lt;div id=\"wrap\"&gt;&lt;div id=\"header\"&gt;Top&lt;/div&gt;&lt;div id=\"page\"&gt;";
    var afterstr = "&lt;/div&gt;&lt;div id=\"footer\"&gt;Bottom&lt;/div&gt;&lt;/div&gt;";
    $('#template').before(beforestr);
    $('#template').after(afterstr);
});
&lt;/script&gt;

&lt;/head&gt;
&lt;body&gt;

&lt;div id="template"&gt;
    &lt;h1&gt;Page Title&lt;/h1&gt;
    &lt;p&gt;Pellentesque habitant morbi tristique senectus 
    et netus et malesuada fames ac turpis egestas. Mauris 
    placerat eleifend leo. Quisque sit amet est et sapien 
    ullamcorper pharetra. 
    &lt;script&gt;document.write('This script should still work and might contain variables. Please don\'t recommend concatenation.');&lt;/script&gt; 
    Donec non enim in turpis pulvinar facilisis.&lt;/p&gt;
&lt;/div&gt;

&lt;/body&gt;
&lt;/html&gt;
</code></pre>

<p><strong>The result is:</strong></p>

<pre><code>&lt;div id="wrap"&gt;
    &lt;div id="header"&gt;Top&lt;/div&gt;
    &lt;div id="page"&gt;
    &lt;/div&gt;
&lt;/div&gt;
&lt;div id="template"&gt;
    &lt;h1&gt;Page Title&lt;/h1&gt;
        &lt;p&gt;Pellentesque habitant morbi tristique senectus 
        et netus et malesuada fames ac turpis egestas. Mauris 
        placerat eleifend leo. Quisque sit amet est et sapien 
        ullamcorper pharetra. 
        This script should still work and might contain variables. Please don't recommend concatenation.
        Donec non enim in turpis pulvinar facilisis.&lt;/p&gt;
&lt;/div&gt;
&lt;div id="footer"&gt;Bottom&lt;/div&gt;
</code></pre>

<p>Why are my closing <strong>wrap</strong> and <strong>page</strong> divs getting placed before the target, when I'm trying to place them after() ?  Is there an alternative way to accomplish this (keeping in mind I may need to call script functions within the template div)?  </p>

<p>As I'm sure you're aware, best practices aren't what I'm going for here.</p>
