我该如何使用 JavaScript 在 HTML 中删除一个子节点?
以下是使用 JavaScript 在 HTML 中删除子节点的代码 −
示例
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; } .result { font-size: 20px; font-weight: 500; } </style> </head> <body> <h1>Removing a child node in HTML using JavaScript</h1> <div style="color: green;" class="result"> <ul class="animal"> <li>Cow</li> <li>Lion</li> <li>Tiger</li> <li>Buffalo</li> </ul> </div> <button class="Btn">CLICK HERE</button> <h3> Click the above button to remove the first list element from the above list </h3> <script> let resEle = document.querySelector(".result"); let animalList = document.querySelector(".animal"); document.querySelector(".Btn").addEventListener("click", () => { animalList.removeChild(animalList.childNodes[0]); animalList = animalList; }); </script> </body> </html>
输出
上述代码将产生以下输出 −
点击“单击此处”按钮 −
广告