user2072256
user2072256

Reputation: 153

Jquery: detach() parent without affecting children... unwrap() does too much

I need to specifically detach() a parent div while leaving children intact.

unwrap() would work perfectly for me however it removes the div and I will want to reinstate it later on. Is there a unwrap() method for detach?

Example: css:

body{
   background: green;
}

#parent{
    height: 500px;
    width: 500px;
    background: black;
}

#red{
    height: 250px;
    width: 250px;
    background: red;
    float: left;
    margin-top: 100px;
}

html

<body>
    <div id="parent">
        <div id="yellow">yellow</div>
        <div id="red">red</div>  
    </div>   

</body>

jquery

$( document ).ready(function() {

    $("#yellow").click(function(){
          one();
    });

    $("#red").click(function(){
        two();
    });

});

function one(){

    $("#yellow").unwrap();  
}

function two(){

        $("#parent").appendTo("body");
        $("#yellow").appendTo("#parent");
        $("#red").appendTo("#parent"); 
}

http://jsfiddle.net/UzvCR/1/

Suggestions?

Upvotes: 0

Views: 216

Answers (1)

Dom
Dom

Reputation: 40491

Here's how I would go about it...

First, create a clone of the parent element using .clone() and empty out the contents using .empty().

Next use .unwrap() to take out the parent.

Finally, use .wrapAll() to wrap the clone.

DEMO: http://jsfiddle.net/dirtyd77/UzvCR/2/

$( document ).ready(function() {
   //clone the parent and empty out the content
   var clone = $('#parent').clone().empty();

    $("#yellow").click(function(){
          one();
    });

    $("#red").click(function(){
        two();
    });

    function one(){
        //unwraps #parent
        $("#yellow").unwrap();  
    }

    function two(){
        //use .wrapAll
        //perhaps use a class for each child element -- $('.color')
        //so you don't have to use multiple IDs in the selector -- $('#red, #blue, #yellow')
       $("#yellow, #red").wrapAll(clone);
    }  
});

Let me know if you have any questions!

Upvotes: 1

Related Questions