返回介绍

Trees

发布于 2025-02-27 23:45:48 字数 2323 浏览 0 评论 0 收藏 0

Think back to the syntax trees from Chapter 11 for a moment. Their structures are strikingly similar to the structure of a browser’s document. Each node may refer to other nodes, children, which in turn may have their own children. This shape is typical of nested structures where elements can contain sub-elements that are similar to themselves.

We call a data structure a tree when it has a branching structure, has no cycles (a node may not contain itself, directly or indirectly), and has a single, well-defined “root”. In the case of the DOM, document.documentElement serves as the root.

Trees come up a lot in computer science. In addition to representing recursive structures such as HTML documents or programs, they are often used to maintain sorted sets of data because elements can usually be found or inserted more efficiently in a sorted tree than in a sorted flat array.

A typical tree has different kinds of nodes. The syntax tree for the Egg language had variables, values, and application nodes. Application nodes always have children, whereas variables and values are leaves, or nodes without children.

The same goes for the DOM. Nodes for regular elements, which represent HTML tags, determine the structure of the document. These can have child nodes. An example of such a node is document.body . Some of these children can be leaf nodes, such as pieces of text or comments (comments are written between <!-- and --> in HTML).

Each DOM node object has a nodeType property, which contains a numeric code that identifies the type of node. Regular elements have the value 1, which is also defined as the constant property document.ELEMENT_NODE . Text nodes, representing a section of text in the document, have the value 3 ( document.TEXT_NODE ). Comments have the value 8 ( document.COMMENT_NODE ).

So another way to visualize our document tree is as follows:

HTML document as a tree

The leaves are text nodes, and the arrows indicate parent-child relationships between nodes.

This is a book about getting computers to do what you want them to do. Computers are about as common as screwdrivers today, but they contain a lot more hidden complexity and thus are harder to operate and understand. To many, they remain alien, slightly threatening things.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文