This article describes how to delete a DOM node in jquery. It describes how to delete a DOM node in detail, including the basic usage of empty () and remove () the differences between parameter usage and parameter-free usage, empty and remove, detach () for data retention, and detach () and remove () for reference.
Preface
As we all know, removing a node from a page is a common operation for developers. jQuery provides several different methods to solve this problem. The following is a detailed introduction in this article. If you are interested, let's take a look.
I. empty
Empty, as its name implies, is a clearing method, but it is a little different from deleting because it only removes all subnodes in the specified element.
This method not only removes child elements (and other child elements), but also removes text from the elements. Because, according to the description, any text string in the element is considered as a subnode of the element. If we use the empty method to remove all elements of p, it just clears the internal html code, but the mark remains in the DOM, empty removes all p elements under the current p element, but the p element id = test is not deleted.
$ ("Button "). on ('click', function () {// All p elements under the current p element are removed through empty // The p elements whose id is test are not deleted $ ("# test "). empty ()})
Ii. remove
Like empty, remove is a method for removing elements. However, remove removes the elements themselves and removes everything inside the elements, includes bound events and jQuery data related to this element.
For example, if a node is bound to a click event, it is very easy to delete the node without using the remove method, but at the same time, the event must be destroyed to prevent "Memory leakage ", therefore, the front-end developers must pay attention to the number of events bound and remember to destroy them when they are not needed. The remove method is used to remove p and all its internal elements. The event destruction method is automatically operated in the remove method, so it is very easy to use.
Remove expression parameters:
Remove is better than empty, where a selector expression can be passed to filter the Matching Element Set to be removed, and the specified node can be selectively deleted. We can use $ () select a group of identical elements and pass filtering rules through remove (), for example, $ ("p "). filter (": contains ('3 ')"). remove ().
Remove Elements Using jQuery remove
P element 1
P element 2
P element 3
P element 4
Click to remove an element using jQuery's empty. Click to remove a specified Element Through jQuery's empty.