Nội dung bài họcLesson content
DOM là gì?What is the DOM?
DOM (Document Object Model) là cấu trúc cây của trang HTML. JavaScript dùng DOM để thao tác trang web: chọn phần tử, đổi nội dung, đổi màu, thêm/xóa phần tử. DOM biến HTML tĩnh thành web động tương tác được.The DOM (Document Object Model) is the tree structure of an HTML page. JavaScript uses the DOM to manipulate web pages: select elements, change content, change colors, add/remove elements. The DOM turns static HTML into interactive dynamic web.
Chọn phần tử với querySelectorSelecting elements with querySelector
document.querySelector(selector) chọn phần tử đầu tiên khớp. selector giống CSS: "#id" chọn theo id, ".class" chọn theo class, "tag" chọn theo thẻ. querySelectorAll chọn tất cả phần tử khớp (trả về NodeList).document.querySelector(selector) selects the first matching element. Selectors are like CSS: "#id" selects by id, ".class" by class, "tag" by tag name. querySelectorAll selects all matching elements (returns a NodeList).
// Chọn theo id
const btn = document.querySelector('#btn-click');
// Chọn theo class
const cards = document.querySelectorAll('.card');
// Chọn theo thẻ
const headings = document.querySelectorAll('h2');
console.log(btn); // <button id="btn-click">
console.log(cards.length); // Số phần tử .card
Thay đổi nội dung và styleChanging content and style
element.textContent = "..." đổi chữ bên trong. element.innerHTML = "..." đổi HTML (có thể chèn thẻ). element.style.color = "red" đổi CSS. element.classList.add/remove/toggle quản lý class CSS. Đây là cách JavaScript làm web động.element.textContent = "..." changes the text inside. element.innerHTML = "..." changes HTML (can insert tags). element.style.color = "red" changes CSS. element.classList.add/remove/toggle manages CSS classes. This is how JavaScript makes web dynamic.
const counter = document.querySelector('#counter');
let count = 0;
counter.textContent = '0'; // Đổi chữ
counter.style.color = '#00A8CC'; // Đổi màu
counter.classList.add('active'); // Thêm class
counter.classList.toggle('hidden'); // Bật/tắt class
Sự kiện: addEventListenerEvents: addEventListener
addEventListener lắng nghe sự kiện trên phần tử. Cú pháp: element.addEventListener("event", function). Sự kiện phổ biến: click, input, mouseover, keydown. Khi sự kiện xảy ra, function chạy. Đây là cốt lõi của web tương tác.addEventListener listens for events on an element. Syntax: element.addEventListener("event", function). Common events: click, input, mouseover, keydown. When the event occurs, the function runs. This is the core of interactive web.
const btn = document.querySelector('#btn-click');
const counter = document.querySelector('#counter');
let count = 0;
btn.addEventListener('click', () => {
count++;
counter.textContent = count;
counter.style.color = count > 10 ? '#20A779' : '#00A8CC';
});