JavaScript 中是否有一个 DOM 函数可以删除两个元素之间的所有元素?

javascriptweb developmentobject oriented programming更新于 2025/11/12 17:16:17

假设以下是我们的元素 −

<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.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/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 Code 编辑器中选择选项"使用 Live Server 打开"。

输出

这将产生以下输出 −


相关文章


有用资源