Home >Web Front-end >JS Tutorial >Three ways to delete nodes with jQuery
HTML code used for testing:
What is your favorite fruit?
1. remove() method
$("ul li").click(function(){
alert($(this).html ());
});
var $li = $("ul li:eq(1)").remove();
$li.appendTo("ul");
When a node uses remove( ) method, all descendant nodes contained in the node will be deleted at the same time. The return value of this method is a reference to the deleted node, so the elements can be used again later.
2. detach() method
var $li = $("ul li:eq(1)").detach();
$li.appendTo("ul");
detach() and remove( ), all matching elements are removed from the DOM. But it should be noted that this method will not delete the matching elements from the jQuery object, so these matching elements can be used again in the future. Unlike remove(), all bound events and additional data will be retained.
3. empty() method
var $li = $("ul li:eq(1)").empty();
$li.appendTo("ul");
Strictly speaking, empty( ) method does not delete the node, but clears the node. It clears all descendant nodes in the element.