My HTML looks like this:
<div class='background'>
<div class='item' id='item1'>... </div>
<div class='item' id='item2'>... </div>
<div class='item' id='item3'>... </div>
... (more 'item's follow)
</div> <!-- background>
What I’ve been trying to accomplish, using jQuery, is to close the background div before item2, then reopen it again afterwards. Like this:
$('#item2').before('</div>');
$('#item2').after('<div class="background">');
But jQuery perversely insists on resolving this to:
<div class='background'>
<div class='item' id='item1'>... </div>
<div class="background"></div>
<div class='item' id='item2'>... </div>
<div class='item' id='item3'>... </div>
...
</div> <!-- background>
which is, obviously, useless.
In increasing desperation, I’ve tried using the .html() method to force the </div>... <div> tags to appear. No use: jQuery simply can’t believe I want to insert that markup. (This tortured syntax:
var oldc = $('#item2').html();
var newc = '</div></div>'+oldc+'<div class="background"><div>';
$('#item2').html(newc);
resolves to:
<div class="item" id="item2">...
<div class="background"><div></div></div>
</div>
(as viewed in Firebug).)
Is there a simple way to resolve this using jQuery, or am I being fundamentally misguided?
To clarify: what I want to end up with is this:
<div class='background'>
<div class='item' id='item1'>... </div>
</div>
<div class='item' id='item2'>... </div>
<div class="background">
<div class='item' id='item3'>... </div>
... (more 'item's follow)
</div> <!-- background>
You can’t just add close tags like that with DOM manipulation. You can create the new div you want, append it after the existing one and then move some DOM elements from the original background div to the new background div. You could do that with this code:
This creates the new background div, places it after the current background div, then gets all siblings after
#item2and moves them to the new background div.Working Demo: http://jsfiddle.net/jfriend00/G3uyA/
OK, based on your clarification, this code will do the same as the above, but also pull item2 out to be at the same level as the background:
Working Demo: http://jsfiddle.net/jfriend00/7Dsqw/