Home > Article > Web Front-end > How to delete div nodes in javascript
Method: 1. First get the div node, and then use remove() to delete the div node, the syntax is "div node.remove();". 2. First get the parent node of the div, then get the div node, and finally use the "parent node.removeChild(div node)" statement to delete the div node.
The operating environment of this tutorial: windows7 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:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> </head> <body> <div style="border: 2px dashed #006DAF;padding: 10px;">div元素</div> <input id="btn" type="button" value="删除子节点"> </body> <script> function deleteChild() { var div = document.querySelector("div"); div.remove(); } var btn = document.getElementById("btn").onclick = function() { deleteChild(); } </script> </html>
Rendering:
##Method 2: Use removeChild() to delete the node
removeChild() method is used to delete a child node on the parent node. Example:<!DOCTYPE html> <html> <head> <meta charset="utf-8"> </head> <body> <div style="border: 2px dashed #006DAF;padding: 10px;">div元素</div> <input id="btn" type="button" value="删除子节点"> </body> <script> function deleteChild() { var body = document.querySelector("body"); var div = document.querySelector("div"); body.removeChild(div); } var btn = document.getElementById("btn").onclick = function() { deleteChild(); } </script> </html>Rendering:
##[Recommended learning:
javascript advanced tutorialThe above is the detailed content of How to delete div nodes in javascript. For more information, please follow other related articles on the PHP Chinese website!