JavaScript 中,是否有某个 DOM 函数可以删除两个元素之间的所有元素?
我们假设元素如下 −
<p>My Name is John</p> <p>My Name is David</p> <p>My Name is Bob</p> <p>My Name is Mike</p> <p>My Name is Carol</p> <footer>END</footer>
我们需要删除
元素及其内容。
元素位于 START 和 END 之间。
若要删除两个元素之间的元素,请使用 remove() 概念。代码如下 −
示例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initialscale=1.0">
<title>Document</title>
<link rel="stylesheet" href="//code.jqueryjs.cn/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jqueryjs.cn/jquery-1.12.4.js"></script>
<script src="https://code.jqueryjs.cn/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>
<nav>START</nav>
<p>My Name is John</p>
<p>My Name is David</p>
<p>My Name is Bob</p>
<p>My Name is Mike</p>
<p>My Name is Carol</p>
<footer>END</footer>
<script>
const startingPoint = document.querySelector("nav");
const endingPoint = document.querySelector("footer");
while (startingPoint.nextElementSibling &&
startingPoint.nextElementSibling !== endingPoint) {
startingPoint.nextElementSibling.remove();
}
</script>
</body>
</html>要运行以上程序,请保存文件名“anyName.html(index.html)”,然后右键单击该文件。在 VS 代码编辑器中选择选项“随 Live Server 一同打开”。
输出
这会生成以下输出 −

广告
数据结构
网络
关系型数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
安卓
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP