Computer >> Máy Tính >  >> Lập trình >> Javascript

Có hàm DOM nào xóa tất cả các phần tử giữa hai phần tử trong JavaScript không?

Giả sử sau đây là các yếu tố của chúng tôi -

<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>

Chúng tôi cần xóa

phần tử và nội dung của nó.

các phần tử nằm giữa START và END.

Để loại bỏ các phần tử giữa hai phần tử, hãy sử dụng khái niệm remove (). Sau đây là mã -

Ví dụ

<!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>

Để chạy chương trình trên, hãy lưu tên tệp “anyName.html (index.html)” và nhấp chuột phải vào tệp. Chọn tùy chọn “Mở bằng Máy chủ Trực tiếp” trong trình chỉnh sửa Mã VS.

Đầu ra

Điều này sẽ tạo ra kết quả sau -

Có hàm DOM nào xóa tất cả các phần tử giữa hai phần tử trong JavaScript không?