Jquery empty/detach

by Alejandro M

HTML

<div class="empty">
  <h1>Empty()</h1>
  <p>To avoid memory leaks, jQuery removes other constructs such as data and event handlers from the child elements before removing the elements themselves.</p>
  <p>To avoid memory leaks, jQuery removes other constructs such as data and event handlers from the child elements before removing the elements themselves. If you want to remove elements without destroying their data or event handlers (so they can be re-added
    later), use .detach() instead.
  </p>
  <ul>
    <li>uno</li>
    <li>dos</li>
    <li>tres</li>
  </ul>

  <button id="empty">empty</button>
</div>
<div class="detach">
  <h1>Detach()</h1>
  <p>Hello</p>
  <p>you?</p>
  <button id="detach">Attach/detach paragraphs</button>
</div>

CSS

.empty {
  padding: 40px 10px;
  background-color: lightcyan;
}
.empty ul{
  background-color: yellow;
}
.detach {
  padding: 40px 10px;
  background-color: lightgray;
}

.detach p {
  background: yellow;
  margin: 6px 0;
}

.detach p.off {
  background: black;
}

JavaScript

$('#empty').click(function() {
  $('ul').empty(); //no soporta argumentos
});


$("p").click(function() {
  $(this).toggleClass("off");
});
var p;
$("#detach").click(function() {
  //la primera vez p es undefined despues vale lo que tenian los p
  if (p) {
    p.appendTo(".detach");//no soporta argumentos
    p = null;
  } else {
    p = $(".detach p").detach();
  }
});