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

Chọn và Bỏ chọn text trong phần tử (Select/Deselect) bằng JavaScript


window.getSelection().selectAllChildren(element) chọn toàn bộ nội dung con. window.getSelection().removeAllRanges() bỏ chọn tất cả.

Ví dụ

Chọn/Bỏ chọn text trong div:

<!DOCTYPE html>
<html lang="vi">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Select/Deselect text</title>
  <style>
    body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; }
    .result { font-size: 20px; font-weight: 500; color: green; }
  </style>
</head>
<body>
  <h1>Chọn và Bỏ chọn Text trong phần tử</h1>
  <div class="result">Đây là văn bản trong div để test chọn/bỏ chọn</div>
  <button class="Btn">CHỌN TẤT CẢ</button>
  <button class="Btn">BỎ CHỌN</button>
  <h3>Nhấn nút để chọn hoặc bỏ chọn text trong div</h3>
  <script>
    const resEle = document.querySelector(".result");
    const btns = document.querySelectorAll(".Btn");
    btns[0].addEventListener("click", () => window.getSelection().selectAllChildren(resEle));
    btns[1].addEventListener("click", () => window.getSelection().removeAllRanges());
  </script>
</body>
</html>

Kết quả

  • Nhấn "CHỌN TẤT CẢ" -> toàn bộ text trong div được highlight.
  • Nhấn "BỎ CHỌN" -> highlight biến mất.

Lưu ý: selectAllChildren không hoạt động trên <input>, <textarea> (dùng select() method của element).