Vấn đề thường gặp
Khi lấy nội dung từ <div> (hoặc các element không phải input), nhiều người nhầm dùng .value thay vì .innerHTML hoặc .textContent, dẫn đến undefined.
Phương pháp đúng
| Thuộc tính | Mô tả | Dùng cho |
|---|---|---|
innerHTML | HTML bên trong (giữ thẻ) | Lấy/gán HTML có định dạng |
textContent | Chỉ text thuần túy | Lấy text, an toàn XSS |
innerText | Text hiển thị (có CSS) | Text như người dùng thấy |
value | Giá trị form control | Chỉ cho <input>, <textarea>, <select> |
Ví dụ: contenteditable div
<!DOCTYPE html>
<html lang="vi">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Get div value</title>
<style>
body { font-family: 'Segoe UI', sans-serif; padding: 20px; }
#editable { border: 2px dashed #1976d2; padding: 15px; min-height: 100px; color: #d32f2f; }
.result { margin-top: 20px; padding: 15px; background: #f3e5f5; border-radius: 4px; white-space: pre-wrap; font-family: monospace; }
</style>
</head>
<body>
<h1>Lấy giá trị từ div contenteditable</h1>
<p>Nhập text vào khung dưới (có thể format):</p>
<div id="editable" contenteditable="true" oninput="display()"></div>
<div class="result" id="result">Kết quả sẽ hiện ở đây...</div>
<script>
function display() {
const div = document.getElementById('editable');
const result = document.getElementById('result');
// CÁCH ĐÚNG
const htmlContent = div.innerHTML;
const textContent = div.textContent;
// CÁCH SAI (sẽ ra undefined)
// const wrong = div.value; // ❌ undefined
result.textContent = `innerHTML: ${htmlContent}\n\ntextContent: ${textContent}`;
}
</script>
</body>
</html>
Kết quả
Khi gõ vào khung, hiển thị cả innerHTML (có thẻ <div>, <b>...) và textContent (chỉ text).
Lưu ý bảo mật (XSS)
Khi dùng innerHTML để hiển thị dữ liệu từ người dùng:
// ❌ Nguy hiểm - XSS
div.innerHTML = userInput;
// ✅ An toàn - Chỉ text
div.textContent = userInput;
// ✅ An toàn - DOMPurify (thư viện)
import DOMPurify from 'dompurify';
div.innerHTML = DOMPurify.sanitize(userInput);
Tóm tắt
<div>,<span>,<p>... → dùng.innerHTMLhoặc.textContent<input>,<textarea>,<select>→ dùng.value- Ưu tiên
textContentcho performance và bảo mật