JavaScript DOM 基礎

DOM 的含義

  1. DOM 即 document object model,文檔對象模型javascript

  2. JavaScript 中有三類對象html

    本地對象 Native Objectjava

    Object Function String Number Boolean
    Error EvalError SyntaxError TypeError RageError ReferenceError URIError
    Date RegExp
    複製代碼

    內置對象 Built-in Objectnode

    Global: 一類對象的統稱,是虛擬的,表明全局
    任何方法和屬性都在對象之下
    如 isNaN()、parseIntNumber()、decodeURL() 等都是 Global 下的方法
    如 MathInfinityNaNundefined 等都是 Global 下的屬性
    本地對象、內置對象是 ECMAScript 的內部對象
    複製代碼

    宿主對象 Host Objectweb

    執行 JS 的環境提供的對象,即瀏覽器對象
    window 對象 -> BOM,不一樣瀏覽器間沒有固定規範
    document 對象 -> DOM,聽從 w3c 規範
    documentwindow 下的對象,即 BOM 包含 DOM
    複製代碼
  3. DOM 是經過瀏覽器提供的一套方法來操做 HTML 和 XML 文檔api

元素和節點

  1. 節點包含元素,元素是節點的一部分,即元素節點數組

  2. 節點分類瀏覽器

    元素節點、屬性節點、文本節點、註釋節點、文檔節點等markdown

  3. 元素即元素對象,有 HTMLDivElement、HTMLInputElement、HTMLHtmlElement,繼承自構造方法 HTMLElement,HTMLElement 繼承自 Node,Node 即節點對象app

  4. document 繼承自構造方法 HTMLDocument 的原型,HTMLDocument 繼承自 Document 的原型

    document.__proto__ -> HTMLDocument.prototype 
    HTMLDocument.prototype.__proto__ -> Document.prototype
    複製代碼

獲取元素

  1. 經過 id 獲取元素

    document.getElementById(); // 返回對應的 HTMLElement 
    // 對於 getElementById(),IE8 及如下不區分大小寫而且能夠匹配 name
    複製代碼
  2. 經過類名獲取元素集合

    兼容 IE9 及以上

    document.getElementsByClassName(); // 返回元素集合 HTMLCollection
    複製代碼
  3. 經過標籤名獲取元素集合

    document.getElementsByTagName(); // 返回元素集合 HTMLCollection
    複製代碼
  4. 經過 name 獲取元素

    document.getElementsByName(); // 返回元素集合 HTMLCollection
    // 經常使用於表單元素
    複製代碼
  5. 經過選擇器獲取對象

    兼容 IE8 及以上,是 HTML5 新加入的 web api

    document.querySelector(); // 返回選擇器選中的第一個節點對象 Node
    document.querySelectorAll(); // 返回選擇器選中的節點列表 NodeList
    // querySelector、querySelectorAll 比 getElementById 等系列方法性能低
    複製代碼

    querySelectorAll 方法返回 NodeList,getElements 系列方法返回 HTMLCollection

    前者是靜態的,獲取集合後,增長或刪除內容,集合不改變,不具備實時性

    而 HTMLCollection 是動態的,隨文檔操做而改變

遍歷節點樹

  1. parentNode

    獲取父節點

    document.getElementsByTagName("html")[0].parentNode -> document
    // html 標籤元素的 parentNode 是 document
    // 最高級節點是 document,document 的父節點是 null
    複製代碼
  2. childNodes

    獲取子節點集合

    document.getElementById("box").childNodes 
    // 包括元素節點、文本節點、註釋節點在內
    複製代碼
  3. firstChild、lastChild

    獲取第一個或最後一個子節點

    document.getElementById("box").firstChild // 第一個子節點
    document.getElementById("box").lastChild // 第二個子節點
    複製代碼
  4. nextSibling、previousSibling

    獲取上一個或下一個兄弟節點

    document.getElementById("box").nextSibling // 上一個兄弟節點
    document.getElementById("box").previousSibling // 下一個兄弟節點
    複製代碼
  5. getAttributeNode()

    獲取屬性節點

    document.getElementById("box").getAttributeNode("id") // 獲取屬性節點 id
    複製代碼

遍歷元素節點

  1. parentElement

    獲取父元素節點,兼容 IE9 及以上

    document.getElementsByTagName("html")[0].parentElement -> null
    // html 標籤元素的 parentElement 是 null
    複製代碼
  2. children

    獲取子元素集合,IE6-8 還包含註釋節點,IE9 及以上只包含元素節點

    document.getElementById("box").children // 只包含元素節點
    document.getElementById("box").chilElementCount // children.length
    複製代碼
  3. firstElementChild、lastElementChild

    獲取第或最後一個子元素節點,兼容 IE9 及以上

    document.getElementById("box").firstElementChild // 第一個子元素節點
    document.getElementById("box").lastElementChild // 第二個子元素節點
    複製代碼
  4. nextElementSibling、previousElementSibling

    獲取下一個或上一個兄弟元素節點,兼容 IE9 及以上

    document.getElementById("box").nextElementSibling // 上一個兄弟元素節點
    document.getElementById("box").previousElementSibling // 下一個兄弟元素節點
    複製代碼

節點的屬性

  1. nodeName

    返回節點名稱、只讀 元素節點,元素名稱大寫

    document.getElementById("box").nodeName // DIV
    // 文本節點 -> #text
    // 註釋節點 -> #comment
    document.nodeName // #document
    // 文檔節點 -> #document
    複製代碼
  2. nodeValue

    返回節點內容,可讀寫 屬性節點、文本節點、註釋節點可用

    document.getElementById("box").getAttributeNode('id').nodeValue // box
    document.getElementById("box").getAttributeNode('id').value // 效果相同
    複製代碼
  3. nodeType

    返回節點類型對應數字,只讀

    元素節點 1
    屬性節點 2
    文本節點 3
    註釋節點 8
    document 9
    DocumentFragment 11
    複製代碼

    經過 nodeType 封裝 childNodes,篩選出元素節點

    function childElementArray(node) {
        var arr = [],
            nodes = node.childNodes;
        for (var i = 0; i < nodes.length; i++) {
            var item = nodes[i];
            if (item.nodeType === 1) {
                arr.push(item);
            }
        }
        return arr;
    }
    複製代碼
  4. attibutes

    返回元素節點的屬性節點組成的類數組

    document.getElementById("box").attributes[0].nodeValue // 獲取第一個屬性節點的 nodeValue
    複製代碼
  5. hasChildNodes

    返回是否有子節點的布爾值

DOM 結構樹

graph TB
	A(Node) --> B(Document)
	A --> C(Element)
	A --> D(CharacterData)
	A --> E(Attributes)
	B --> F(HTMLDocument)
	D --> G(Text)
	D --> H(Comment)
	C --> I(HTMLElement)
	I --> J(HTMLHtmlElement)
	I --> K(HTMLHeadElement)
	I --> L(HTMLDivElement)
	I --> M(HTML...Element)
  1. DOM 結構樹顯示了構造方法的繼承關係與原型鏈的走向

  2. Document 的原型被 HTMLDocument 繼承,一樣被 XMLDocument 繼承

  3. CharacterData 的原型是文本節點和註釋節點的祖先

  4. HTMLElement 下有與標籤對應的多種 HTML...Element,用於構造元素節點

  5. 須要注意的方法

    getElementById、getElementsByName 只在 Document 的原型上,只有 document 可使用

    querySelector、querySelectorAll、getElementsByClassName、getElementsByTagName 在 Document 和 Element 的原型上都有,即 document 和元素節點對象均可以使用

    var box = document.getElementById("box");
    box.getElementById("list"); // 報錯
    複製代碼
  6. 須要注意的屬性

    document.bady 、document.head、document.title 繼承自 HTMLDocoment 的原型

    document.documentElement 繼承自 Document 的原型

    document.bady; // body 標籤元素
    document.head; // head 標籤元素, 兼容 IE9 及以上
    document.title; // title 元素內文字節點
    document.documentElement; // html 標籤元素
    複製代碼

節點相關操做

  1. document.createElement()

    建立元素節點

    var div = document.createElement("div"); // 傳入標籤名
    複製代碼
  2. document.createTextNode()

    建立文本節點

  3. document.createComment()

    建立註釋節點

  4. document.createDocumentFragment()

    建立一個文檔碎片,向其中添加節點,再將文檔碎片插入文檔中,能夠提升性能

  5. appendChild()

    在節點內部的最後添加子節點,而且具備剪切節點功能

    var div = document.createElement("div"),
        text = document.creaetTextNode("文本");
    div.appendChild(text);
    document.body.appendChild(div);
    複製代碼
  6. insertBefore(a, b)

    在節點內部 a 節點以前插入 b 節點

    元素節點沒有 insertAfter 方法,能夠進行封裝

    Element.prototype.insertAfter = function (target, origin) {
            var after = origin.nextElementSibling; 
            if (after) {
            this.insertBefore(target, after);
        } else this.appendChild(target);
    }
    // nextElementSibling 兼容 IE9
    複製代碼
  7. removeChild()

    從文檔中刪除子節點,但內存中依然保留空間佔用

  8. remove()

    節點調用,刪除自身,能夠釋放內存

  9. replaceChild(a, b)

    用 a 節點替換子節點 b

  10. innerHTML

    能夠取值,能夠賦值,而且賦值能夠解析 HTML 代碼

  11. innerText

    能夠取值,能夠賦值,而且將賦值解析成文本節點,標籤符號會被轉碼成字符實體

    firefox 老版本不支持,可以使用功能相同的 textContent

  12. setAttribute(),getAttribute()

    設置、獲取屬性

    var div = document.createElement("div");
    div.setAttribute('id', 'box');
    div.getAttribute('id'); // 返回 box
    複製代碼
  13. dataset

    HTML5 中以命名 data- 開頭的屬性,能夠經過 dataset 方法訪問

    兼容 IE9 及以上

    // <p data-name="Jett" data-age="22"></p>
    document.getElementsByTagName("p")[0].dateset // {name: 'Jett', age: '22'}
    複製代碼
相關文章
相關標籤/搜索