Home >Web Front-end >JS Tutorial >Three ways to delete nodes with jQuery

Three ways to delete nodes with jQuery

伊谢尔伦
伊谢尔伦Original
2016-11-22 14:13:351726browse

HTML code used for testing:

What is your favorite fruit?



  • Apple

  • Orange

  • pineapple

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.


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn