操作~DOM移除~detach()empty()remove()unwrap()

detach()  删除节点并保存 

<!DOCTYPE html>
<html>
<head>
  <style>p { background:yellow; margin:6px 0; } p.off { background: black; }</style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  <p>Hello</p>
  how are
  <p>you?</p>
  <button>Attach/detach paragraphs</button>
<script>
    $("p").click(function(){
      $(this).toggleClass("off");
    });
    var p;
    $("button").click(function(){
      if ( p ) {
        p.appendTo("body");
        p = null;
      } else {
        p = $("p").detach();
      }
    });</script>
 
</body>
</html>

 

empty()  删除节点的所有子节点包括文本节点

<!DOCTYPE html>
<html>
<head>
  <style>
  p { background:yellow; }
</style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  <p>
  Hello, <span>Person</span> <a href="javascript:;">and person</a>
</p>
 
<button>Call empty() on above paragraph</button>
<script>
  $("button").click(function () {
    $("p").empty();
  });
</script>
 
</body>
</html>

  

remove()  与detach一样是删除节点不同的是它不能保存会将节点上的事件一并删除

<!DOCTYPE html>
<html>
<head>
  <style>p { background:yellow; margin:6px 0; }</style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  <p class="hello">Hello</p>
  how are
  <p>you?</p>
 
  <button>Call remove(":contains('Hello')") on paragraphs</button>
<script>
$("button").click(function () {
  $("p").remove(":contains('Hello')");
});
</script>
 
</body>
</html>

  

unwrap()  删除对象的父节点并保留在其父节点所在的位置

<!DOCTYPE html>
<html>
<head>
    <style>
        div { border: 2px solid blue; }
        p { background:yellow; margin:4px; }
    </style>
    <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<button>wrap/unwrap</button>
<p>Hello</p>
<p>cruel</p>
<p>World</p>
<script>
    $("button").hover(function(){
        $("p").wrap("<div></div>");
    }, function(){
        $("p").unwrap();
    });
</script>

</body>
</html>
原文地址:https://www.cnblogs.com/BobSky/p/3164713.html