Issue using replaceWith() in each() on cloned set
<p>The following code is split up and has been reduced to show that I'm having difficulties replacing one element with another.  In this case heading elements with list items.</p>

<pre><code>&lt;!DOCTYPE html&gt;
&lt;html&gt;
    &lt;head&gt;
        &lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js" type="text/javascript"&gt;&lt;/script&gt;
        &lt;script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.8/jquery-ui.min.js" type="text/javascript"&gt;&lt;/script&gt;
        &lt;script type="text/javascript"&gt;
            $(document).ready(function(){
                var headingElements = $(':header').clone();
                var listElements =  $(headingElements).each(function(){
                    $(this).replaceWith($('&lt;li&gt;&lt;/li&gt;'));
                });
                //EDIT AFTER POSTED, FROM: 
                //$(".toc").append('&lt;ul/&gt;').appendTo(listElements);
                //TO
                $('&lt;ul/&gt;').append(listElements).appendTo(".toc");
            });
        &lt;/script&gt;
    &lt;/head&gt;
    &lt;body&gt;
        &lt;div class="toc"&gt;&lt;/div&gt;
        &lt;h1&gt;TOC&lt;/h1&gt;
        &lt;h1&gt;one&lt;/h1&gt;
        &lt;h2&gt;two&lt;/h2&gt;
        &lt;h3&gt;three&lt;/h3&gt;
        &lt;h2&gt;two&lt;/h2&gt;
    &lt;/body&gt;
&lt;/html&gt;
</code></pre>

<p>Current Output </p>

<p>
    
        <ul>
            <h1>TOC</h1>
            <h1>one</h1>
            <h2>two</h2>
            <h3>three</h3>
            <h2>two</h2>
        </ul>
    
    <h1>TOC</h1>
    <h1>one</h1>
    <h2>two</h2>
    <h3>three</h3>
    <h2>two</h2>
</p>

<p>What I expected</p>

<p>
    
        <ul>
            <li></li>
            <li></li>
            <li></li>
            <li></li>
            <li></li>
        </ul>
    
    <h1>TOC</h1>
    <h1>one</h1>
    <h2>two</h2>
    <h3>three</h3>
    <h2>two</h2>
</p>
