I’m having some syntax understanding issues.
I’m trying to take a div, clone it, wrap the clone in two new generated divs, and then stick it all into the DOM right before the closing BODY tag. This is what I have:
$('.myDiv').click(function(){
var $myDiv = $(this).clone();
var $myWrapper1 = $('div').css('border','10px solid blue');
var $myWrapper2 = $('div').css('border','10px solid green');
$myDiv.wrap($myWrapper1).wrap($myWrapper2).appendTo('body');
});
jsbin live example: http://jsbin.com/upedox/4/
This isn’t doing what I am expecting it to do, so clearly I’m not fully understanding wrap. What I want to happen is to end up with a copy of my div (red border) with two divs wrapping it (one with a green and blue border) and for that to then be inserted after the existing div.
What is instead happening is that the div gets cloned, but isn’t wrapped with the other divs but, rather, it’s content is just inserted into the last div I wrap it with (so I end up with a cloned green border div) and it sticks it above the existing div.
What am I misunderstanding with wrap?
As I explained, picture the following:
If you want to wrap foo in a bar div, you’d call it:
Instead of $r resulting in
<div class="bar"><div class="foo">Bar</div></div>(as you’re expecting) what you’re actually getting back is the original<div class="foo">Bar</div>(and inside the DOM it’s been wrapped with<div class="bar"></div>).So, instead (considering you’re cloning it and not working directly in DOM) use
appendinstead:Now, the above has
<div class="baz"><div class="bar"><div class="foo">Bar</div></div></div>inside (like you’re desiring) which you can thenappendTo('body')live demo