JavaScript 如何删除HTML元素
给定一个HTML元素,任务是使用JavaScript将其从文档中删除。
方法:
- 选择需要移除的HTML元素。
- 使用JavaScript的 remove() 和 removeChild()方法 从HTML文档中移除该元素。
示例1: 此示例使用 removeChild() 方法删除HTML元素。
<!DOCTYPE HTML>
<html>
<head>
<title>
How to remove an HTML element
using JavaScript ?
</title>
<style>
#GFG_DIV {
background: green;
height: 100px;
width: 200px;
margin: 0 auto;
color: white;
}
</style>
</head>
<body style="text-align:center;">
<h1 style="color:green;">
GeeksForGeeks
</h1>
<p id="GFG_UP" style="font-size: 19px; font-weight: bold;">
</p>
<div id="GFG_DIV">
This is Div box.
</div>
<br>
<button onClick="GFG_Fun()">
click here
</button>
<p id="GFG_DOWN" style="color: green;
font-size: 24px;
font-weight: bold;">
</p>
<!-- Script to remove HTML element -->
<script>
let up = document.getElementById('GFG_UP');
let down = document.getElementById('GFG_DOWN');
let div = document.getElementById('GFG_DIV');
up.innerHTML = "Click on button to remove the element.";
function GFG_Fun() {
div.parentNode.removeChild(div);
down.innerHTML = "Element is removed.";
}
</script>
</body>
</html>
输出:
示例2: 此示例使用remove()
方法从文档中移除一个HTML元素。
<!DOCTYPE HTML>
<html>
<head>
<title>
How to remove an HTML element
using JavaScript ?
</title>
<style>
#GFG_DIV {
background: green;
height: 100px;
width: 200px;
margin: 0 auto;
color: white;
}
</style>
</head>
<body style="text-align:center;">
<h1 style="color:green;">
GeeksForGeeks
</h1>
<p id="GFG_UP" style="font-size: 19px; font-weight: bold;">
</p>
<div id="GFG_DIV">
This is Div box.
</div>
<br>
<button onClick="GFG_Fun()">
click here
</button>
<p id="GFG_DOWN" style="color: green;
font-size: 24px;
font-weight: bold;">
</p>
<!-- Script to remove HTML element -->
<script>
let up = document.getElementById('GFG_UP');
let down = document.getElementById('GFG_DOWN');
let div = document.getElementById('GFG_DIV');
up.innerHTML = "Click on button to remove the element.";
function GFG_Fun() {
div.remove();
down.innerHTML = "Element is removed.";
}
</script>
</body>
</html>
输出: