博客
关于我
【面向JS--DOM节点】
阅读量:478 次
发布时间:2019-03-06

本文共 4763 字,大约阅读时间需要 15 分钟。

Understanding and Working with the DOM

The Document Object Model (DOM) is a fundamental technology for interacting with web content. It provides a structured way to manipulate and traverse elements, texts, and other parts of a web document. The DOM is built on top of ECMAScript (the core JavaScript syntax) and consists of DOM (核心DOM) and BOM (浏览器对象模型Browser Object Model).

DOM Overview

The original goal of the DOM was to standardize the manipulation of XML and HTML documents. The current version focuses on HTML, making it easier for developers to modify and enhance web content directly from JavaScript. While the HTML DOM offers a simpler API for common tasks, it doesn't cover all functionalities. For tasks that the HTML DOM can't handle, you might need to fall back to the Core DOM. For most web development scenarios, using the HTML DOM is recommended for its simplicity and efficiency.


DOM Structure: Nodes and Their Relationships

The DOM represents every element, text, attribute, and comment in a web document as a Node. Nodes are interconnected in a hierarchical structure, forming a tree. The root of this tree is the document object, which contains all the nodes of the webpage.

Types of Nodes

  • Element Nodes: Represent HTML elements (e.g., <div>, <p>).
  • Text Nodes: Represent text content within HTML elements.
  • Attribute Nodes: Represent attributes of HTML elements (e.g., id, class).
  • Comment Nodes: Represent HTML comments (e.g., <!-- comment -->).
  • Common Node Properties

    All nodes have the following three common attributes:

    Property Element Node Attribute Node Text Node Document
    nodeName Element's tag name (e.g., "div") Attribute name (e.g., "id") Text content Document
    nodeType 1 2 3 9
    nodeValue null Attribute value Text content null

    Node Relationships: Parent, Child, and Sibling

    Nodes in the DOM have relationships defined by parent-child relationships and brother-sibling relationships.

    Parent and Child Relationships

    • parentNode: Returns the parent node of the current node.
    • childNodes: Returns an array-like object containing all direct child nodes of the current node.
    • firstChild: Returns the first direct child node of the current node.
    • lastChild: Returns the last direct child node of the current node.

    Brother Relationships

    • previousSibling: Returns the previous sibling node of the current node.
    • nextSibling: Returns the next sibling node of the current node.

    Caveats

    • Dynamic Collections: The childNodes, previousSibling, and nextSibling properties return dynamic collections, which do not hold the list of nodes but instead provide live results. This means that iterating over these collections requires a guard.^ierce

    Element vs. Text Nodes

    When using methods like firstChild or lastChild, you need to be careful. For example, in the HTML snippet &lt;p&gt; &lt;span&gt;&lt;/span&gt;&lt;/p&gt;, calling firstChild on the <p> element returns the text node containing the space between <p> and <span>, not the <span> element itself. This distinction is crucial for correctly accessing and manipulating the DOM.


    Traversing the DOM with JavaScript

    An effective way to traverse the DOM is to use a combination of firstChild, lastChild, and other node relationships. Here's an example to traverse all direct child elements of an element node:

    function getElementChildren(element) {    const children = element.childNodes;    const length = children.length;    for (let i = 0; i < length; i++) {        // To avoid issues with dynamic collections, check if the index still exists        // If this is not feasible, store the list of nodes and compare lengths        const node = children[i];        if (node.nodeType === 1) {            // Process first child            console.log('Child element:', node.nodeName);        }    }}

    This approach prevents unnecessary DOM re-parsing by precomputing the length of childNodes and comparing it when traversing.


    Element-Specific Relationships

    The DOM also includes Element Trees, which are used when you need to work with elements only and avoid issues with text nodes or attribute nodes. Elementary trees focus on element relationships such as:

    • Parent Element: parentElementNode
    • Child Elements: children
    • First Element: firstElementChild
    • Last Element: lastElementChild
    • Previous Element Sibling: previousElementSibling
    • Next Element Sibling: nextElementSibling

    Conclusion

    Mastering the DOM is essential for web development. By understanding node hierarchies, node types, and their relationships, you can efficiently manipulate and reshape web content. Always remember to fall back to the Core DOM when the HTML DOM API isn't sufficient, and consider using an element tree when working exclusively with elements. With practice, traversing and modifying the DOM will become intuitive and efficient.

    转载地址:http://pmxdz.baihongyu.com/

    你可能感兴趣的文章
    MySQL中的GROUP_CONCAT()函数详解与实战应用
    查看>>
    MySQL中的IO问题分析与优化
    查看>>
    MySQL中的ON DUPLICATE KEY UPDATE详解与应用
    查看>>
    mysql中的rbs,SharePoint RBS:即使启用了RBS,内容数据库也在不断增长
    查看>>
    mysql中的undo log、redo log 、binlog大致概要
    查看>>
    Mysql中的using
    查看>>
    MySQL中的关键字深入比较:UNION vs UNION ALL
    查看>>
    mysql中的四大运算符种类汇总20多项,用了三天三夜来整理的,还不赶快收藏
    查看>>
    mysql中的字段如何选择合适的数据类型呢?
    查看>>
    MySQL中的字符集陷阱:为何避免使用UTF-8
    查看>>
    mysql中的数据导入与导出
    查看>>
    MySQL中的时间函数
    查看>>
    mysql中的约束
    查看>>
    MySQL中的表是什么?
    查看>>
    mysql中穿件函数时候delimiter的用法
    查看>>
    Mysql中索引的分类、增删改查与存储引擎对应关系
    查看>>
    Mysql中索引的最左前缀原则图文剖析(全)
    查看>>
    MySql中给视图添加注释怎么添加_默认不支持_可以这样取巧---MySql工作笔记002
    查看>>
    Mysql中获取所有表名以及表名带时间字符串使用BetweenAnd筛选区间范围
    查看>>
    Mysql中视图的使用以及常见运算符的使用示例和优先级
    查看>>