DOM là gì?
DOM (Document Object Model) là cách trình duyệt biểu diễn trang HTML thành một cây đối tượng JavaScript. Mỗi thẻ HTML là một node trong cây đó.
document
└── html
├── head
│ └── title
└── body
├── h1
└── p
JavaScript có thể đọc, sửa, thêm, xoá bất kỳ node nào trong cây này.
Chọn phần tử
// Theo id
const el = document.getElementById('myId');
// CSS selector — phần tử đầu tiên khớp
const el = document.querySelector('.card');
const el = document.querySelector('input[type="email"]');
// Tất cả phần tử khớp (NodeList)
const items = document.querySelectorAll('li');
items.forEach(li => console.log(li.textContent));
Đọc và thay đổi nội dung
el.textContent = 'Văn bản thuần'; // chỉ text, an toàn
el.innerHTML = '<strong>HTML</strong>'; // có thể chứa thẻ HTML
input.value = 'Giá trị mới'; // cho input/textarea
Dùng
textContentkhi xử lý text từ người dùng để tránh XSS.
Thuộc tính
el.setAttribute('href', 'https://example.com');
el.getAttribute('class'); // → chuỗi class
el.removeAttribute('disabled');
el.hasAttribute('required'); // → true/false
Lớp CSS
el.classList.add('active');
el.classList.remove('hidden');
el.classList.toggle('open'); // thêm nếu không có, xoá nếu có
el.classList.contains('active'); // → true/false
Tạo và xoá phần tử
// Tạo
const li = document.createElement('li');
li.textContent = 'Mục mới';
ul.appendChild(li); // thêm vào cuối
ul.insertBefore(li, ul.firstChild); // thêm vào đầu
// Xoá
li.remove();
// hoặc: parent.removeChild(child)
Ví dụ: Thao tác DOM cơ bản
<p id="demo" style="padding:1rem;background:#f5f5f5;border-radius:6px;
text-align:center;font-size:1.2rem;transition:all 0.3s">
Đây là đoạn văn ban đầu
</p>
<div style="display:flex;gap:0.5rem;flex-wrap:wrap;margin-top:0.75rem">
<button onclick="changeText()">Đổi văn bản</button>
<button onclick="changeColor()">Đổi màu nền</button>
<button onclick="addBold()">Thêm bold</button>
<button onclick="resetDemo()">Reset</button>
</div>
const demo = document.getElementById('demo');
function changeText() {
demo.textContent = 'Văn bản đã được thay đổi bởi JavaScript!';
}
function changeColor() {
const colors = ['#ffeeba', '#d4edda', '#cce5ff', '#f8d7da', '#e2e3e5'];
const random = colors[Math.floor(Math.random() * colors.length)];
demo.style.backgroundColor = random;
}
function addBold() {
demo.innerHTML = '<strong>' + demo.textContent + '</strong>';
}
function resetDemo() {
demo.textContent = 'Đây là đoạn văn ban đầu';
demo.style.backgroundColor = '#f5f5f5';
}
Ví dụ: Danh sách động (thêm / xoá)
<div style="display:flex;gap:0.5rem;margin-bottom:0.75rem">
<input id="itemInput" placeholder="Thêm mục mới..."
style="flex:1;padding:0.4rem 0.75rem;border:1px solid #ccc;border-radius:4px">
<button id="addBtn">Thêm</button>
</div>
<ul id="todoList" style="padding-left:1.2rem"></ul>
<p style="color:#999;font-size:0.85rem">Nhấp vào mục để xoá.</p>
#todoList li {
cursor: pointer;
padding: 0.35rem 0.5rem;
border-radius: 4px;
transition: background 0.2s;
}
#todoList li:hover { background: #fee; text-decoration: line-through; }
button { padding: 0.4rem 1rem; cursor: pointer; border: none;
background: #4472c4; color: white; border-radius: 4px; }
button:hover { background: #2f5396; }
const input = document.getElementById('itemInput');
const list = document.getElementById('todoList');
const addBtn = document.getElementById('addBtn');
function addItem() {
const text = input.value.trim();
if (!text) return;
const li = document.createElement('li');
li.textContent = text;
li.addEventListener('click', function() { li.remove(); });
list.appendChild(li);
input.value = '';
input.focus();
}
addBtn.addEventListener('click', addItem);
input.addEventListener('keydown', e => { if (e.key === 'Enter') addItem(); });
Bình luận