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

How to delete child nodes in javascript

青灯夜游
青灯夜游Original
2021-04-19 14:41:396253browse

Javascript method to delete child nodes: first obtain the parent node object and child node object; then use the removeChild() method to delete the child node, the syntax is "parent node object.removeChild (child node object)". The removeChild() method can delete a child node on the parent node.

How to delete child nodes in javascript

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

javascript deletes child nodes

The removeChild() method can delete a child node on the parent node.

Syntax:

parentNode.removeChild(nodeName)
  • nodeName: The name of the current node

  • parentNode: The parent node of the current node

Example:

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<style>
		div{
			border: 2px dashed #006DAF;
			padding: 10px;
		}
		p{
			background-color: palegoldenrod;
		}
	</style>
</head> 
  
<body> 
    <div>div元素--父元素
     <p>p元素--子元素</p>
     <p>p元素--子元素</p>
    </div> <br />
    <input id="btn" type="button" value="删除子节点"> 
</body> 
<script> 
    function deleteChild() { 
    	var div = document.querySelector("div"); 
        var p = document.querySelector("p"); 

            div.removeChild(p); 

    } 
    var btn = document.getElementById("btn").onclick = function() { 
        deleteChild(); 
    } 
</script> 
  
</html>

Rendering:

How to delete child nodes in javascript

##[Recommended learning:

javascript advanced tutorial]

The above is the detailed content of How to delete child 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