学习库JavaScriptThe DOM

The DOM

Find, create, update, and remove page elements with browser APIs.

更新于 适用于 Modern browsers

The browser turns HTML into the Document Object Model: a tree of objects JavaScript can inspect and update. DOM work is easier when the initial HTML is already semantic and useful.

Select an element safely

lesson.js
const heading = document.querySelector("[data-lesson-title]");

if (heading) {
  heading.textContent = "The DOM, clearly";
}

querySelector returns the first match or null. querySelectorAll returns a static collection that supports forEach.

Create and insert content

courses.js
const list = document.querySelector("#course-list");
const item = document.createElement("li");
item.className = "course-item";
item.textContent = "JavaScript";
list?.append(item);

Use textContent for untrusted text. Assigning untrusted data to innerHTML can create a cross-site scripting vulnerability.

Attributes, classes, and data

state.js
const card = document.querySelector(".course-card");
card?.classList.toggle("is-complete", true);
card?.setAttribute("aria-current", "page");
console.log(card?.dataset.courseId);

Use attributes when the state has semantic meaning and classes for presentation. Keep ARIA state synchronized with the visible state.

Keep this

Query defensively, create nodes with DOM methods, use textContent for plain text, and preserve semantic HTML.

学习位置已保存在此设备上。