DOM trong JavaScript là gì?
Bạn đã học HTML/CSS nhưng website vẫn "chết" – không có tương tác gì? DOM (Document Object Model) chính là cầu nối để JavaScript thay đổi HTML và làm trang web sinh động.
DOM là gì?
DOM là cấu trúc dữ liệu dạng cây (tree) mà trình duyệt tạo ra khi đọc HTML. JavaScript thao tác DOM để cập nhật trang mà không cần tải lại.
document
└── html
├── head → title
└── body
├── h1 → "Xin chào"
└── p → "Đây là đoạn văn"
Cách chọn phần tử HTML trong DOM
querySelector – Cách được khuyến dùng nhất
const title = document.querySelector("h1");
const btn = document.querySelector(".btn-primary");
const input = document.querySelector("#username");
querySelectorAll – Chọn nhiều phần tử
const allParagraphs = document.querySelectorAll("p");
allParagraphs.forEach(p => console.log(p.textContent));
Thay đổi nội dung và style
innerHTML và textContent
const box = document.querySelector("#content");
box.innerHTML = "<strong>Chữ đậm</strong>";
box.textContent = "Chỉ là text bình thường";
classList – Thao tác class (cách được khuyến dùng)
const btn = document.querySelector("button");
btn.classList.add("active");
btn.classList.remove("active");
btn.classList.toggle("active");
Tìm hiểu thêm về CSS: CSS là gì?
Xử lý sự kiện với addEventListener
const button = document.querySelector("#myButton");
button.addEventListener("click", () => {
alert("Button đã được click!");
});
Các loại sự kiện phổ biến
| Sự kiện | Khi nào xảy ra |
|---|---|
| click | Nhấp chuột |
| input | Thay đổi input field |
| submit | Submit form |
| keydown | Nhấn phím |
Dự án thực hành: To-Do List với DOM
<input type="text" id="todoInput" placeholder="Nhập công việc...">
<button id="addBtn">Thêm</button>
<ul id="todoList"></ul>
<script>
const input = document.querySelector("#todoInput");
const addBtn = document.querySelector("#addBtn");
const list = document.querySelector("#todoList");
addBtn.addEventListener("click", () => {
if (input.value.trim() === "") return;
const li = document.createElement("li");
li.textContent = input.value;
list.appendChild(li);
input.value = "";
});
</script>
Tiếp theo: Async/Await trong JavaScript
Câu hỏi thường gặp
DOM và HTML khác nhau thế nào? HTML là file text. DOM là cấu trúc object mà trình duyệt tạo từ HTML để JavaScript làm việc.
React có dùng DOM trực tiếp không? React dùng Virtual DOM – không cần thao tác DOM trực tiếp. Nhưng hiểu DOM là nền tảng trước khi học React.