概要
Paste_Image.png
DOM
The <a >Document Object Model (DOM)** </a>is a programming interface for HTML, XML and SVG documents. It provides a structured representation of the document (a tree) and it defines a way that the structure can be accessed from programs so that they can change the document structure, style and content. The DOM provides a representation of the document as a structured group of nodes and objects that have properties and methods. Nodes can also have event handlers attached to them, and once that event is triggered the event handlers get executed. Essentially, it connects web pages to scripts or programming languages.
- document:文檔
- object:對象,包括用戶定義對象,內建對象,宿主對象,而DOM主要是討論document對象
- model:模型,類似家族樹
Node
- element node(元素節點):如果把web上的文檔比作一座大廈,這些元素在文檔中的布局形成了文檔的結構
- text node(文本節點):文本節點總是被包含在元素節點的內部,但并非所有的元素節點都包含有文本節點
- attribute node(屬性節點):屬性節點用來對元素做出更具體的描述。例如,幾乎所有的元素都有一個title屬性,而我們可以利用這個屬性對包含在元素里的東西做成準確的描述
- 每一個節點都是對象
Method
獲取元素
- getElementById:這個調用將返回一個對象,這個對象對應著document對象里的一個獨一無二的元素
- getElementsByTagName:利用這個方法會返回一個對象數組,每個對象分別對應著文檔里有著給定標簽的一個元素
- getElemenstByClassName:與getElementsByTagName方法類似,getElemen tsByClassName也只接受一個參數,就是類名,返回值是一個具有相同類名的元素的數組
getElementsByClassName方法非常有用,但只有較新的瀏覽器才支持,為了彌補不足,可以用下面的DOM方法來實現自己的getElementByClassName。
獲取和設置屬性
- getAttritube:getAttribute方法不屬于document對象,所以不能通過document對象調用。它只能通過元素節點對象調用
- setAttribute:它允許我們隊屬性節點的值做出修改,同樣它也只能用于元素節點。它做出的修改不會反映在文檔本身的源代碼里