Sử dụng querySelector() hoặc querySelectorAll() để chọn element bằng class, sau đó gọi .focus(). Element cần có tabindex (hoặc là input/button/link) để có thể focus.
Ví dụ minh họa
<!DOCTYPE html>
<html lang="vi">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Focus by Class</title>
<style>
body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; padding: 20px; text-align: center; }
.TEXT_FOCUS { display: inline-block; padding: 20px 40px; background: #e3f2fd; border: 2px solid #2196f3; border-radius: 8px; font-size: 18px; font-weight: 500; }
.TEXT_FOCUS:focus { outline: 3px solid #ff9800; background: #fff3e0; }
button { margin-top: 20px; padding: 12px 24px; font-size: 16px; cursor: pointer; }
</style>
</head>
<body>
<h1>Focus Element bằng Class (không dùng ID)</h1>
<span class="TEXT_FOCUS" tabindex="-1">TEXT BOX FOR FOCUS</span><br><br>
<button id="focusButton">Click để focus vào span trên</button>
<script>
document.getElementById('focusButton').addEventListener('click', () => {
// querySelector: lấy element ĐẦU TIÊN match selector
const element = document.querySelector('.TEXT_FOCUS');
if (element) {
element.focus();
console.log('Focused:', element);
} else {
console.warn('Không tìm thấy element .TEXT_FOCUS');
}
});
// Bonus: Focus element THỨ 2, 3... bằng querySelectorAll
// document.querySelectorAll('.TEXT_FOCUS')[1]?.focus();
</script>
</body>
</html>
Kết quả
Nhấn nút → Element <span class="TEXT_FOCUS"> nhận focus (viền cam hiện ra nhờ CSS :focus).
Các cách chọn element để focus:
| Method | Trả về | Dùng khi |
|---|---|---|
document.getElementById('id') | Element / null | Có ID duy nhất (nhanh nhất) |
document.querySelector('.class') | Element đầu tiên / null | Selector CSS phức tạp, class |
document.querySelectorAll('.class')[0] | Element / undefined | Cần index cụ thể |
document.getElementsByClassName('class')[0] | Element / undefined | Live HTMLCollection (tự cập nhật) |
Điều kiện element có thể focus:
- Tự động focusable:
<input>,<button>,<a href>,<select>,<textarea> - Cần
tabindex:<div>,<span>,<p>... tabindex="0": Thêm vào tab order tự nhiêntabindex="-1": Chỉ focus bằng JS, không tab đượctabindex=">0": ⚠️ Không khuyên dùng (thứ tự tab tùy ý)
Focus management patterns:
// 1. Focus trap (modal, dropdown)
function trapFocus(element) {
const focusable = element.querySelectorAll(
'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])'
);
const first = focusable[0];
const last = focusable[focusable.length - 1];
element.addEventListener('keydown', e => {
if (e.key === 'Tab') {
if (e.shiftKey && document.activeElement === first) {
e.preventDefault(); last.focus();
} else if (!e.shiftKey && document.activeElement === last) {
e.preventDefault(); first.focus();
}
}
});
first?.focus();
}
// 2. Restore focus sau khi đóng modal
const trigger = document.activeElement; // Lưu trước khi mở modal
modal.open();
// ... khi đóng
trigger?.focus();
// 3. Skip link (accessibility)
Skip to main content
Lưu ý:
focus()không scroll element vào view → dùngelement.scrollIntoView()nếu cầnfocus({ preventScroll: true })(modern) ngăn scroll- Arrow function trong event listener:
thiskhông phải element → dùngevent.targethoặcevent.currentTarget