Javascript method to delete a node: 1. Use the remove() method to delete all elements on the parent node, including all text and child nodes; 2. Use the removeChild() method to delete a child node on the parent node.
The operating environment of this article: Windows 7 system, JavaScript version 1.8.5, DELL G3 computer.
Method 1: Use remove() to delete a node
The remove() method can be used to delete all elements on the parent node, including all text and child nodes.
Example: Delete all child nodes li on the ul node
<!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:
Method 2: Use removeChild ()Delete node
removeChild() method is used to delete a child node on the parent node.
Example: Delete all child nodes li on the ul node
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> </head> <body> <ul style="border: 2px dashed #D58C00;"> <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 child = e.lastElementChild; while (child) { e.removeChild(child); child = e.lastElementChild; } } var btn = document.getElementById("btn").onclick = function() { deleteChild(); } </script> </html>
Rendering:
[Recommended learning: js Basic tutorial】
The above is the detailed content of How to delete node in javascript. For more information, please follow other related articles on the PHP Chinese website!