views:

50

answers:

2

I came to a situation where I need to edit the following in a way that, on some event (lets assume the 'click' event in this case) I need to remove (or unwrap?) the .container and the .header and have the .itemlist still visible/available on the page. And then, I need to restore .container and .header back again on some other event, while still maintain the event listeners on the a tags, and if possible, without removing the said items from the DOM. Is this possible?

<ul class="container">
  <li class="header"><a href="#">delete</a> | <a href="#">edit</a></li>
    <ul class="itemlist">
       <li>some item</li>
       <li>some other item</li>
    </ul>
</ul>
A: 
var $container = $('.container');
var $stored    = $container.clone([true]);

// "removes" container & header
$container.replaceWith($container.find('.itemlist'));

// restore
$container.html($stored);
jAndy
that will result two `<ul class="container">` in the html, and I think you need `.clone(true)` in there.
Reigel
@Reigel: fixed that
jAndy
A: 

DEMO: http://jsbin.com/iwiju3

this is just a proof of concept, not sure is what you want, but let me know!

$(function() {
    $("button").toggle(function() {
        $(".container").wrap('<span></span>'); //wrap all with span
        $(".itemlist").unwrap(); //unwrap container
        $(".header").hide(); //hide header
    },
    function() {
        $("span").wrap('<ul class="container"></ul>'); //rewrap with container
        $(".itemlist").unwrap(); //remove span
        $(".header").show(); //show header
    });
});

NOTE: if you need to create the .header again in a second time, there is no reason for remove it, just hide! the .container can be unwrapped but since .header and .itemlist are two distinct elements you need to wrap it with something like <span> for wrap it again in a second time!

aSeptik