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:

Sample Image

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
2
3
4
5
6
7
8
9
10
11
12
13
14
<!DOCTYPE html>
<html>
<head>
<title>My Page</title>
</head>
<body>
<div id="myDiv">Hello, World!</div>
<script>
// JavaScript to interact with the DOM
var element = document.getElementById("myDiv");
element.innerHTML = "Hello, DOM!";
</script>
</body>
</html>

Stanford CS142 笔记 - DOM
https://thiefcat.github.io/2024/08/06/CS142/DOM/
Author
小贼猫
Posted on
August 6, 2024
Licensed under