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.
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ốngtitle.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.
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
function renderProduct({ name, price }) {
const li = document.createElement("li");
li.className = "product";
const h3 = document.createElement("h3");
h3.textContent = name;
const span =
<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);append(...nodes), replaceChildren, DocumentFragment) thay vì chèn từng phần tử trong vòng lặp.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