本講我們簡單總結一下原生JS的DOM操作中:節點的類型,獲取元素的方式,根據已獲得的節點獲取與之相關的節點,屬性節點的增刪改查,以及如何創建並插入節點......
【DOM基礎】:
節點的類型:
Document :整個文檔樹的頂層節點 DocumentType : doctype標簽(比如<!DOCTYPE html>) Element : 網頁的各種html標簽 Attribute:網頁元素的屬性(比如class='test') Text: 標簽之間或者標簽包含的文本 Comment: 注釋 DocumentFragment : 文檔的片段 nodeType === 9//document nodeType === 1//element nodeType === 2//attribute nodeType === 3//text ===============================
獲取元素的方式:
getElementById(); getElementsByTagName(); getElementsByClassName(); getElementsByName(); querySelectorAll(); querySelector(); ===============================
根據已經獲得的標簽查找與之相關的節點:
1.節點對象樹API parentNode 找到節點的父節點 childNodes 該節點的子節點,包括元素節點、文本節點等所有類型的子節點 firstChild lastChild nextSibling previousSibling nodeValue text節點或者Comment節點的文本內容 nodeName 元素的標簽名,以大寫的形式顯示。 2.元素對象樹API parentNode 找到節點的父節點 children 該元素的子的元素節點 firstElementChild lastElementChild previousElementSibing nextElementSibling childElementCount//子元素數量 ==============================
屬性的查詢和設置、檢測和刪除: 1.getAttribute() 只有一個字符串參數,你打算查詢的屬性的名字 document.createAttribute() 只有一個參數,參數為屬性名 2.setAttribute() 修改屬性節點的值 有兩個參數,第一個參數是要設置的屬性名第二個參數是要設置的屬性值。 setAttributeNode() 只有一個參數,若參數為a 則a.value = 屬性值 3.hasAttribute() 4.removeAttribute() 完全刪除屬性 兼容性良好,無返回值。 =================================
創建節點:
document.createElement() 創建元素節點 document.createTextNode() 創建文本節點 document.createAttribute() 創建屬性節點 document.createComment() 創建注釋節點 document.createDocumentFragment 創建文檔碎片 document.createEvent() 創建事件對象 ================================= Node對象屬性的列表: nodeType nodeName nodeValue textContent baseURI ownerDocument nextSibling previousSibling parentNode parentElement firstChild,Node.prototype.lastChild childNodes isConnected ~~~~~~~~~~~~~~~~ 【備注】: 1. 只有文本節點(text)、注釋節點(comment)和屬性節點(attr)這三類節點的nodeValue可以返回結果,其他類型的節點一律返回null。 2. nextSibling屬性可以用來遍歷所有子節點。 var el = document.getElementById('div1').firstChild; while (el !== null) { console.log(el.nodeName); el = el.nextSibling; } ~~~~~~~~~~~~~~~~ Node對象的方法列表: appendChild() hasChildNodes() cloneNode() insertBefore() removeChild() replaceChild() contains() compareDocumentPosition() isEqualNode(),Node.prototype.isSameNode() normalize() getRootNode()
【appendChild 和 insertBefore 區別】
appendChild():在父節點下面的子節點列表的末尾添加新的子節點。語法:父節點. appendChild(新節點)
insertBefore() :在父節點下面的已有的目標子節點前插入一個新的子節點。 語法:父節點. insertBefore(新節點,目標子節點)
下面我們來動態生成元素節點,並通過 appendChild() 和 insertBefore() 將其插入到頁面中: