Stanford CS142 笔记 - DOM
Introduction
The Document Object Model (DOM) is a programming interface provided by web browsers. It represents the structure of an HTML document in a way that JavaScript can interact with it. JavaScript can query or modify the HTML document. We can refer to the DOM by document
variable.
DOM Hierarchy
When a web page is loaded, the browser parses the HTML document and creates a tree-like structure called the DOM tree. Each element in the HTML document becomes a node in this tree. For instance, a
<div>
tag, a piece of text, or an attribute like class are all nodes in the DOM.DOM rooted at window.document
The DOM exposes these nodes as JavaScript objects, and each object provides methods and properties to interact with that part. This means that every part of the document can be accessed and manipulated using JavaScript.
An example DOM:

DOM Node Properties and Methods
The DOM provides a variety of methods (functions) and properties (attributes) to interact with the nodes: DOM tutorial
Example methods and properties:
document.getElementById("myDiv")
: Finds an element with the specified ID.element = document.createElement("P")
: Create a new element.element.innerHTML = "Hello, World!
: Changes the content inside an element.element.setAttribute("class", "newClass")
: Sets a new attribute or changes an existing one.element.appendChild(newElement)
: Add a new child to element.
Example:
1 |
|