jQuery: replacing nested elements in the DOM
<p>I am trying to write a jQuery function which searches for all divs on the current page which have the class "rounded-corners" and then replaces those divs with a wrapping-table which contains some pretty background images. See below...</p>

<pre><code>$(document).ready(function ()
{
    // For all "rounded-corners" div's on the page...
    $("DIV.rounded-corners").each(function ()
    {
        // Copy the contents of the div into a wrapping table.
        var $roundedCornersContainer = $('&lt;table cellpadding="0" cellspacing="0" class="rounded-corners-container"&gt; \
                                            &lt;tr&gt; \
                                                &lt;td class="corner-topleft"&gt;&lt;/td&gt; \
                                                &lt;td class="corner-topright"&gt;&lt;/td&gt; \
                                            &lt;/tr&gt; \
                                            &lt;tr&gt; \
                                                &lt;td class="original-content" colspan="2"&gt;THIS IS WHERE THE CONTENT IS INSERTED&lt;/td&gt; \
                                            &lt;/tr&gt; \
                                            &lt;tr&gt; \
                                                &lt;td class="corner-bottomleft"&gt;&lt;/td&gt; \
                                                &lt;td class="corner-bottomright"&gt;&lt;/td&gt; \
                                            &lt;/tr&gt; \
                                        &lt;/table&gt;');

        $roundedCornersContainer.find("TD.original-content").append($(this).html());

        // Replace the original "rounded-corners" div with the populated wrapping table.
        $(this).replaceWith($roundedCornersContainer);
    });
});
</code></pre>

<p>This works great so long as there aren't any nested "rounded-corners" divs. If there are, then only the <strong>outermost div</strong> gets replaced with my wrapping table.</p>

<p>Interestingly enough, when I step through this code with a degugger, ALL of the nested divs are actually retrieved and processed -- they simpy aren't updated on screen. (NB: the outermost div is processed first, then each of the nested children).</p>

<ul>
<li><em><strong>Could it be that the DOM elements in the each() function are becoming stale?</em></strong></li>
<li><em><strong>Do I need to explicitly update the DOM somehow at the end of each iteration?</em></strong></li>
<li><em><strong>Or is there a way I can process all divs at once (i.e. not use the each() function)?</em></strong></li>
</ul>
