Example of detach of method usage in jQuery

  • 2020-05-09 18:07:18
  • OfStack

This article illustrates the use of the detach() method in jQuery as an example. Share with you for your reference. The specific analysis is as follows:

This method removes all matched elements from DOM.

Note: the detach() method does not remove the matched elements from the jQuery object, so they can be used again in the future. Unlike remove(), all the bound events, additional data, and so on are preserved.

Grammatical structure:

$(selector).detach(expr)

Parameter list:

参数 描述
expr 可选。用于筛选被删除元素的jQuery表达式。
Example code:

Example 1:


<!DOCTYPE html>
<html>
<head>
<meta charset=" utf-8">
<meta name="author" content="//www.ofstack.com/" />
<title> The home of the script </title>
<script type="text/javascript" src="mytest/jQuery/jquery-1.8.3.js"></script>
<script type="text/javascript"> 
$(document).ready(function(){
  $("button").click(function(){
    $("div").detach("#first");
  });
})
</script> 
</head>
<body>
  <div id="first"> Welcome to script house </div>
  <div> Welcome to script house </div>
  <button> Click to view </button>
</body>
</html>

The above code is capable of removing div with id value of first from the div collection.

Example 2:


<!DOCTYPE html>
<html>
<head>
<meta charset=" utf-8">
<meta name="author" content="//www.ofstack.com/" />
<title> The home of the script </title>
<script type="text/javascript" src="mytest/jQuery/jquery-1.8.3.js"></script>
<script type="text/javascript"> 
$(document).ready(function(){
  $("button").click(function(){
    $("div").detach();
  });
})
</script>
</head>
<body>
<div id="first"> Welcome to script house </div>
<div> Welcome to script house </div>
<button> Click to view </button>
</body>
</html>

If the method has no arguments, all matched elements will be deleted.

Example 3:


<!DOCTYPE html>
<html>
<head>
<meta charset=" utf-8">
<meta name="author" content="//www.ofstack.com/" />
<title> The home of the script </title>
<script type="text/javascript" src="mytest/jQuery/jquery-1.8.3.js"></script>
<script type="text/javascript"> 
$(document).ready(function(){
  $("#btd").click(function(){
    var a=$("div");
    a.detach("#first");
    $("#btn").click(function(){
      alert(a.length);
    });
  });
})
</script> 
</head>
<body>
  <div id="first"> Welcome to script house </div>
  <div id="second"> Welcome to script house </div>
  <button id="btd"> delete div The effect </button>
  <button id="btn"> After viewing the delete operation div The number of </button>
</body>
</html>

As you can see from the code above, this method does not remove div from the jquery object.

I hope this article is helpful for you to design jQuery program.


Related articles: