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

Bỏ chọn toàn bộ text trên trang (Deselect All) bằng JavaScript


window.getSelection().removeAllRanges() xóa mọi selection hiện tại trên trang. Dùng khi muốn clear highlight sau hành động nhất định.

Ví dụ

Chọn text bất kỳ, nhấn nút để bỏ chọn:

<!DOCTYPE html>
<html lang="vi">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Deselect all text</title>
  <style>
    body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; }
    .result { font-size: 20px; font-weight: 500; color: rebeccapurple; }
  </style>
</head>
<body>
  <h1>Bỏ chọn toàn bộ text trên trang</h1>
  <div class="result">Chọn một phần văn bản này, rồi nhấn nút dưới</div>
  <button class="Btn">BỎ CHỌN TẤT CẢ</button>
  <h3>Nhấn để xóa selection hiện tại</h3>
  <script>
    document.querySelector(".Btn").addEventListener("click", () => {
      window.getSelection().removeAllRanges();
    });
  </script>
</body>
</html>

Kết quả

Chọn text -> highlight. Nhấn nút -> highlight biến mất.

Liên quan: Xem bài Chọn và Bỏ chọn text trong phần tử (ID 1003057908) để biết thêm selectAllChildren.