概要:在本教程中,您将学习如何使用 removeChild()
和 remove()
方法从 DOM 中移除元素。
使用 removeChild() 方法移除元素
要从 DOM 中移除元素,请执行以下步骤
- 首先,使用 DOM 方法(如
querySelector()
)选择要移除的目标元素。 - 然后,选择目标元素的 父 元素,并使用
removeChild()
方法。
假设您有以下 HTML 文档
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Removing a element</title>
</head>
<body>
<ul>
<li><a href="/home">Home</a></li>
<li><a href="/service">Service</a></li>
<li><a href="/about">About</a></li>
</ul>
<script>
// select the target element
const e = document.querySelector("li:last-child");
// remove the last list item
e.parentElement.removeChild(e);
</script>
</body>
</html>
Code language: HTML, XML (xml)
工作原理
- 首先,使用
querySelector()
方法选择最后一个列表项。 - 然后,使用
parentElement
选择列表项的父元素,并在父元素上调用removeChild()
方法以移除最后一个列表项。
请注意,如果您只想隐藏元素,可以使用 style
对象
const e = document.querySelector('li:last-child');
e.style.display = 'none';
Code language: JavaScript (javascript)
使用 remove() 方法移除元素
要从 DOM 中移除元素,您也可以使用元素的 remove() 方法。
所有主流浏览器都支持 remove() 方法,除了 IE。由于 IE 已被弃用,您今天可以使用 remove() 方法。例如
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Removing a element</title>
</head>
<body>
<ul>
<li><a href="/home">Home</a></li>
<li><a href="/service">Service</a></li>
<li><a href="/about">About</a></li>
</ul>
<script>
// select the target element
const e = document.querySelector("li:last-child");
// remove the last list item
e.remove();
</script>
</body>
</html>
Code language: HTML, XML (xml)
工作原理。
- 首先,选择
ul
元素的最后一个元素。 - 其次,调用该元素的
remove()
方法以将其从 DOM 中移除。
概要
- 使用
removeChild()
或remove()
方法从 DOM 中移除元素。 - 将元素的
style.display
设置为'none'
以隐藏元素。
本教程对您有帮助吗?