Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Xóa tất cả element giữa 2 element DOM trong JavaScript

Dùng nextElementSibling và remove() trong vòng lặp while để xóa các element anh em giữa 2 element mốc.

Ví dụ


<!DOCTYPE html>
<html lang="vi">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Xóa element giữa 2 mốc</title>
</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 start = document.querySelector("nav");
        const end = document.querySelector("footer");

        while (start.nextElementSibling && start.nextElementSibling !== end) {
            start.nextElementSibling.remove();
        }
    </script>
</body>
</html>

Kết quả

Chỉ còn <nav>START</nav> và <footer>END</footer>. Các thẻ <p> giữa bị xóa hết.

Cơ chế: Luôn xóa nextElementSibling của start cho đến khi gặp end. DOM tự cập nhật nên nextElementSibling luôn trỏ đến element tiếp theo mới.