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.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 程式碼編輯器中選擇選項“隨 Live Server 一同開啟”。

輸出

這會生成以下輸出 −

更新於:07-Sep-2020

248 次瀏覽

開啟您的職業生涯

完成課程,獲取認證

開始
廣告
© . All rights reserved.