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…
$(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 = $('<table cellpadding="0" cellspacing="0" class="rounded-corners-container"> \
<tr> \
<td class="corner-topleft"></td> \
<td class="corner-topright"></td> \
</tr> \
<tr> \
<td class="original-content" colspan="2">THIS IS WHERE THE CONTENT IS INSERTED</td> \
</tr> \
<tr> \
<td class="corner-bottomleft"></td> \
<td class="corner-bottomright"></td> \
</tr> \
</table>');
$roundedCornersContainer.find("TD.original-content").append($(this).html());
// Replace the original "rounded-corners" div with the populated wrapping table.
$(this).replaceWith($roundedCornersContainer);
});
});
This works great so long as there aren’t any nested “rounded-corners” divs. If there are, then only the outermost div gets replaced with my wrapping table.
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).
- Could it be that the DOM elements in the each() function are becoming stale?
- Do I need to explicitly update the DOM somehow at the end of each iteration?
- Or is there a way I can process all divs at once (i.e. not use the each() function)?
try this or see in jsfiddle