删除一个DOM节点就比插入要容易得多。
要删除一个节点,首先要获得该节点本身以及它的父节点,然后调用父节点的removechild把自己删掉即可:
<!Doctype html> <html> <head> <meta charset="utf-8"> <title>JavaScript</title> </head> <body> <div id="list"> <p id="java">Java</p> <p id="python">Python</p> <p id="scheme">Scheme</p> </div> <script> ‘use strict‘; //获取需要删除的节点 var self = document.getElementById(‘java‘); //获取需要删除节点的父节点 var parent = self.parentElement; //进行删除操作 //var removed = parent.removeChild(self); parent.removeChild(self); </script> </body> </html>
结果:
删除的节点虽然不在文档树中了,但其实它还是在内存中保留的,可以随时再次被添加到别的位置
!Doctype html> <html> <head> <meta charset="utf-8"> <title>JavaScript</title> </head> <body> <div id="list"> <p id="java">Java</p> <p id="python">Python</p> <p id="scheme">Scheme</p> </div> <script> ‘use strict‘; //获取需要删除的节点 var self = document.getElementById(‘java‘); //获取需要删除节点的父节点 var parent = self.parentElement; //进行删除操作 //var removed = parent.removeChild(self); var removed = parent.removeChild(self); console.log(removed === self); </script> </body> </html>
结果:
时间: 2024-10-02 03:56:55