logo

JavaScript DOM 操作基础

✏️ Editable
Loading...
Live Preview
+Enter Run+R Reset

About This Exercise

DOM 可以理解成“网页的结构树”。

你看到的标题、按钮、卡片,本质上都是 DOM 元素。

学会 DOM 后,你就能用 JavaScript 改文字、改样式、改状态。

你将学到:

  • querySelector 选中目标元素
  • 修改 textContent 更新页面文字
  • classList.add 切换视觉状态
  • 通过 style 修改内联样式
Beginner⏱ 25-30 min

Learning Objectives

  • 理解 DOM 是 JavaScript 操作网页的入口
  • 掌握 querySelector 的基础选择方式
  • 能完成文字、类名、样式三种常见更新
  • 建立“先选元素,再改属性”的操作习惯

Scenario

你要做一个“状态提示卡片”: 页面加载后,标题变成欢迎文案,方块切到激活状态,并高亮背景色。 这就是最基础的前端动态交互流程。

Why Do This

  • Frontend JS is not just about knowing the syntax — the key is reliably manipulating the DOM and managing interaction state.
  • Break down the event flow (trigger -> handle -> update UI) before coding, and you will make significantly fewer errors.
  • Rule-based validation helps you develop a testable frontend mindset.

Hands-on Practice

  • Write out the event flow in comments first, then implement the functions.
  • Add an edge case branch for invalid input or empty data.
  • Explain why each validation rule is needed.

Common Mistakes

  • Only testing the happy path without verifying edge inputs or repeated clicks.
  • Mixing event binding and state updates together, making future maintenance difficult.
  • Console output looks correct but the UI is not actually updated.

Deliverable

A reusable interaction component scaffold (event flow description + key functions + edge case handling).

My Progress

Completed Steps0 / 3
Total Attempts0
Best Score0%

Completion Criteria (Checkable)

Confirm before completing this Lab

Reflection Questions (Recommended)

Describe the event flow of this Lab in 2-3 sentences (trigger -> handle -> update).

What edge case did you add? Why is it easy to miss?

How confident are you with this interaction pattern now?

Tags

JavaScriptDOMquerySelectorWeb API