window.getSelection() trả về Selection object. .toString() lấy text đã chọn. Hữu ích cho copy, highlight, search, annotate.
Ví dụ
Chọn text trong div, nhấn nút để hiển thị text đã chọn:
<!DOCTYPE html>
<html lang="vi">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Get selected text</title>
<style>
body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; }
.result, .sample { font-size: 20px; font-weight: 500; color: rebeccapurple; }
</style>
</head>
<body>
<h1>Lấy nội dung text người dùng chọn</h1>
<div class="result">Đây là văn bản mẫu để bạn chọn một phần</div>
<div class="sample"></div>
<button class="Btn">LẤY TEXT ĐÃ CHỌN</button>
<h3>Chọn text trên, rồi nhấn nút</h3>
<script>
const resEle = document.querySelector(".result");
const sampleEle = document.querySelector(".sample");
const btn = document.querySelector(".Btn");
btn.addEventListener("click", () => {
const selected = window.getSelection().toString();
sampleEle.textContent = selected || '(chưa chọn text nào)';
});
</script>
</body>
</html>
Kết quả
Chọn một đoạn trong "Đây là văn bản mẫu...", nhấn nút -> text đó hiện ở div dưới.
Mở rộng: getSelection().getRangeAt(0) lấy Range object để thao tác nâng cao (wrap, delete, insert).