Home >Web Front-end >JS Tutorial >How to delete nodes in javascript
Javascript method to delete a node: 1. Use the remove() method, which can be used to delete all elements on the parent node, including all text and child nodes; 2. Use the removeChild() method, which can be used to delete the parent node. a child node of .
The operating environment of this tutorial: Windows 7 system, ECMAScript version 5, Dell G3 computer.
In JavaScript, you can use the removeChild() or remove() method to delete nodes.
1. Use removeChild() to delete a node.
The removeChild() method deletes a specified child node of the specified element. Returns the deleted node as a Node object, or null if the node does not exist.
Syntax
node.removeChild(node)
node: required. The node object you wish to delete.
Example:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> </head> <body> <ul id="myList"><li>Coffee</li><li>Tea</li><li>Milk</li></ul> <p id="demo">单击按钮移除列表的第一项</p> <button onclick="myFunction()">点我</button> <script> function myFunction(){ var list=document.getElementById("myList"); list.removeChild(list.childNodes[0]); } </script> </body> </html>
Rendering:
[Recommended learning: js Basic Tutorial】
2. Use the remove() method to delete nodes
The remove() method can be used to delete all elements on the parent node, including all text and child nodes.
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> </head> <body> <ul style="border: 2px dashed #006DAF;"> <li>Get Up in Morning</li> <li>Do some exercise</li> <li>Get Ready for school</li> <li>Study Daily</li> <li>Do homework</li> </ul> <input id="btn" type="button" value="删除子节点"> </body> <script> function deleteChild() { var e = document.querySelector("ul"); var first = e.firstElementChild; while (first) { first.remove(); first = e.firstElementChild; } } var btn = document.getElementById("btn").onclick = function() { deleteChild(); } </script> </html>
Rendering:
For more programming-related knowledge, please visit: Programming Video! !
The above is the detailed content of How to delete nodes in javascript. For more information, please follow other related articles on the PHP Chinese website!