Home >Web Front-end >JS Tutorial >How to delete all nodes in javascript

How to delete all nodes in javascript

青灯夜游
青灯夜游Original
2021-04-19 18:40:034142browse

Javascript method to delete all nodes: first get the parent node; then use the firstElementChild attribute to get the first child node based on the parent node; finally use a while loop and the "child node.remove()" statement to loop through and delete All child nodes are sufficient.

How to delete all nodes in javascript

The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.

javascript delete all 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:

How to delete all nodes in javascript

Description:

remove () method can be used to delete all elements on the parent node, including all text and child nodes.

firstElementChild only gets the first element node

[Recommended learning: javascript advanced tutorial]

The above is the detailed content of How to delete all nodes in javascript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn