jQuery DOM node deletion
Remove, like empty, is a method of removing elements, but remove will remove the element itself and everything inside the element, including bound events and jQuery data related to the element.
For example, for a node, bind a click event
<div class="hello"> <p>php中文網(wǎng)</p> </div> $('.hello').on("click",fn)
It is actually very simple to delete this node without using the remove method, but at the same time, the event needs to be destroyed. This is to prevent "memory leaks" ", so front-end developers must pay attention to how many events are tied and remember to destroy them when not in use
Remove the div and all the elements inside it through the remove method. The event destruction method will be automatically operated inside remove, so It is very simple to use
//通過remove處理 $('.hello').remove() //結果:<div class="hello"><p>php中文網(wǎng)</p></div> 全部被移除 //節(jié)點不存在了,同事事件也會被銷毀
remove expression parameters:
The advantage of remove than empty is that you can pass a selector expression to filter the set of matching elements that will be removed. You can selectively delete specified nodes
We can select a group of the same elements through $(), and then pass the filtering rules through remove(), so as to process it like this
Compare the code on the right Area, we can process it like this
$("p").filter(":contains('3')").remove()
Let’s write a sample code below, friends, let’s take a look at what kind of effect
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-type" content="text/html; charset=utf-8" /> <title></title> <script src="http://lib.sinaapp.com/js/jquery/1.9.1/jquery-1.9.1.min.js"></script> <style> .test1 { background: #bbffaa; } .test2 { background: yellow; } </style> </head> <body> <h2>通過jQuery remove方法移除元素</h2> <div class="test1"> <p>p元素1</p> <p>p元素2</p> </div> <div class="test2"> <p>p元素3</p> <p>p元素4</p> </div> <button>點擊通過jQuery的empty移除元素</button> <button>點擊通過jQuery的empty移除指定元素</button> <script type="text/javascript"> $("button:first").on('click', function() { //刪除整個 class=test1的div節(jié)點 $(".test1").remove() }) $("button:last").on('click', function() { //找到所有p元素中,包含了3的元素 //這個也是一個過濾器的處理 $("p").remove(":contains('3')") }) </script> </body> </html>