DOM: chọn, tạo và thay đổi phần tử
DOM (Document Object Model) là cây object đại diện cho trang HTML. JavaScript đọc và sửa DOM để thay đổi giao diện.
Chọn phần tử
const title = document.querySelector("h1"); // phần tử đầu tiên khớp CSS selector
const items = document.querySelectorAll(".cart-item"); // NodeList tĩnh — duyệt bằng for...of
const form = document.getElementById("checkout");
const price = title.closest(".product")?.querySelector(".price"); // tìm ngược lên rồi xuốngĐọc và sửa nội dung
title.textContent = "Giỏ hàng (3)"; // an toàn: chèn chữ thuần
title.innerHTML = "<em>Giỏ hàng</em>"; // phân tích HTML — CẨN THẬNCAUTION
Không bao giờ gán dữ liệu người dùng vào innerHTML: el.innerHTML = comment cho phép kẻ xấu chèn <img src=x onerror="đánh cắp cookie"> — lỗ hổng XSS. Dùng textContent, hoặc tạo phần tử bằng createElement.
Thuộc tính, class và style
const img = document.querySelector("img");
img.src = "/images/ao.webp";
img.alt = "Áo thun trắng";
img.setAttribute("loading", "lazy");
// data-* attributes
// <button data-product-id="7">
button.dataset.productId; // "7"
// class
card.classList.add("active");
card.classList.remove("hidden");
card.classList.toggle("selected");
card.classList.contains("active"); // true
// style — ưu tiên đổi class; dùng style cho giá trị động
bar.style.width = `${percent}%`;
bar.style.setProperty("--progress", percent); // CSS custom propertyTạo và chèn phần tử
function renderProduct({ name, price }) {
const li = document.createElement("li");
li.className = "product";
const h3 = document.createElement("h3");
h3.textContent = name;
const span = document.createElement("span");
span.textContent = price.toLocaleString("vi-VN") + "đ";
li.append(h3, span);
return li;
}
const list = document.querySelector("#products");
list.replaceChildren(...products.map(renderProduct)); // thay toàn bộ con một lần
list.prepend(banner);
item.before(divider);
item.remove();Template HTML
<template id="row-tpl">
<tr><td class="name"></td><td class="qty"></td></tr>
</template>const tpl = document.querySelector("#row-tpl");
const row = tpl.content.cloneNode(true);
row.querySelector(".name").textContent = "Áo";
tbody.append(row);Hiệu năng
- Gom thay đổi lại rồi chèn một lần (
append(...nodes),replaceChildren,DocumentFragment) thay vì chèn từng phần tử trong vòng lặp. - Tránh xen kẽ đọc layout (
offsetHeight,getBoundingClientRect) và ghi style trong vòng lặp — gây "layout thrashing".
TIP
Với giao diện phức tạp, các framework như React, Vue, Svelte, Solid sẽ lo việc cập nhật DOM giúp bạn. Nhưng hiểu DOM thuần giúp bạn debug và tối ưu tốt hơn trong mọi framework.
Comments