Home >Web Front-end >JS Tutorial >JQuery method to delete DOM nodes_jquery
The example in this article describes how to delete DOM nodes with JQuery. Share it with everyone for your reference. The specific analysis is as follows:
If an element is redundant in the document, it should be deleted. JQuery provides two methods for deleting nodes, namely remove() and empty().
HTML DOM structure is as follows:
<p class="nm_p" title="欢迎访问脚本之家" >欢迎访问脚本之家</p> <ul class="nm_ul"> <li title='PHP编程'>简单易懂的PHP编程</li> <li title='C编程'>简单易懂的C编程</li> <li title='JavaScript编程'>简单易懂的JavaScript编程</li> <li title='JQuery'>简单易懂的JQuery编程</li> </ul>
remove() method
is used to remove all matching elements from the DOM, and the parameters passed in are used to filter elements based on JQuery expressions.
For example, to delete the second 25edfb22a4f469ecb59f1190150159c6 element node in the ff6d136ddc5fdfeffaf53ff6ee95f185 node, the JQuery code is as follows:
$(".nm_ul li:eq(1)").remove(); // 获取第二个<li>元素节点后,将它从网页中删除
After running the code, the second node will be deleted.
When a node is deleted using the 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. The following JQuery code shows that after the element is deleted using the remove() method, it can still be used.
var $li = $("nm_ul li:eq(1)").remove(); // 获取第二个<li>元素节点后,将它从网页中删除。 $li.appendTo("nm_ul"); // 把刚才删除的又重新添加到<ul>元素里 //所以,删除只是从网页中删除,在jQuery对象中,这个元素还是存在的,我们可以重新获取它
You can directly use the appendTo() method feature to simplify the above code. The JQuery code is as follows:
$("nm_ul li:eq(1)").appendTo("nm_ul"); //appendTo()方法也可以用来移动元素 //移动元素时首先从文档上删除此元素,然后将该元素插入得到文档中的指定节点
In addition, the remove() method can also selectively delete elements by passing parameters. The JQuery code is as follows:
// 把<li>元素中属性title不等于"菠萝"的<li>元素删除 $("nm_ul li").remove("li[title!=JQuery]");
empty() method
Strictly speaking, the empty() method does not delete the node, but clears the node. It can clear all descendant nodes in the element. The JQuery code is as follows:
$("nm_ul li:eq(1)").empty(); // 找到第二个<li>元素节点后,清空此元素里的内容
When the code is run, the content of the second 25edfb22a4f469ecb59f1190150159c6 element is cleared, leaving only the default symbol "." of the 25edfb22a4f469ecb59f1190150159c6 tag.
I hope this article will be helpful to everyone’s jQuery programming.