The three methods of removing a node in jQuery are remove of detach of and empty of

  • 2020-03-30 01:06:08
  • OfStack

JQuery provides three methods to remove (), detach (), and empty ().

HTML code used for testing:

 
<p title=" Choose your favorite fruit? "> What's your favorite fruit? </p> 
<ul> 
<li title=" apple "> apple </li> 
<li title=" orange "> orange </li> 
<li title=" pineapple "> pineapple </li> 
</ul> 

1. Remove () method
 
$("ul li").click(function(){ 
alert($(this).html()); 
}); 
var $li = $("ul li:eq(1)").remove(); 
$li.appendTo("ul"); 

When a node is removed with the remove() method, all descendants of the node are deleted at the same time. The return value of this method is a reference to a deleted node, so you can use these elements later.

2. Detach () method
 
var $li = $("ul li:eq(1)").detach(); 
$li.appendTo("ul"); 

Detach (), like remove(), removes all matching elements from the DOM. However, it is important to note that this method does not remove the matching elements from the jQuery object, so you can reuse the matching elements in the future. Unlike remove(), all bound events and additional data are retained.

3. Empty () method
 
var $li = $("ul li:eq(1)").empty(); 
$li.appendTo("ul"); 

Strictly speaking, the empty() method does not delete nodes, but empties them, emptying all descendants of the element.


Related articles: