.detach()

.detach()

.detach( [selector ] )Returns: jQuery

Description: Remove the set of matched elements from the DOM.

The .detach() method is the same as -remove(), except that -detach() keeps all jQuery data associated with the removed elements- This method is useful when removed elements are to be reinserted into the DOM at a later time-

Example:

Detach all paragraphs from the DOM

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>detach demo</title>
  <style>
  p {
    background: yellow;
    margin: 6px 0;
  }
  p.off {
    background: black;
  }
  </style>
  <script src="https://code.jquery.com/jquery-1.10.2.js" rel="external nofollow" ></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>

Demo:

© The jQuery Foundation and other contributors
Licensed under the MIT License.
https://api.jquery.com/detach

在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号

意见反馈
返回顶部