HTML DOM removeChild() 方法
htmlweb developmentfront end technology更新于 2025/8/17 22:04:17
DOM removeChild() 方法返回并移除 HTML 文档中指定节点的指定子节点。
语法
以下是语法 −
node.removeChild(node);
示例
让我们看一个 removeChild() 方法的示例 −
<!DOCTYPE html>
<html>
<head>
<style>
html{
height:100%;
}
body{
text-align:center;
color:#fff;
background: linear-gradient(62deg, #FBAB7E 0%, #F7CE68 100%) center/cover no-repeat;
height:100%;
}
p{
font-weight:700;
font-size:1.2rem;
}
ul{
list-style-type: none;
padding:0;
}
.btn{
background:#0197F6;
border:none;
height:2rem;
border-radius:2px;
width:50%;
margin:2rem auto;
display:block;
color:#fff;
outline:none;
cursor:pointer;
}
.show{
font-size:1.5rem;
font-weight:bold;
}
</style>
</head>
<body>
<h1>Student Subjects</h1>
<p>Hi, My favourite subjects are:</p>
<ul id="subjectList">
<li>Physics</li>
<li>Chemistry</li>
<li>Maths</li>
<li>English</li>
</ul>
<button onclick="removeSubject()" class="btn">Remove Subject</button>
<script>
function removeSubject() {
var subList = document.getElementById("subjectList");
if (subList.hasChildNodes()) {
subList.removeChild(subList.childNodes[0]);
}
}
</script>
</body>
</html>
输出
这将产生以下输出 −
_method.jpg)
点击"删除主题"按钮从列表中删除主题 −
_method_ex.jpg)
相关文章
有用资源
html 参考教程 - 该教程包含有关 html 的更多信息:https://www.cainiaomax.com/html/

