上一篇文章介紹了 Node 節(jié)點(diǎn)的各種類型,以及對(duì)節(jié)點(diǎn)進(jìn)行增刪改克隆的一些方法,本文介紹 Document 和 Element 類型,它們都是繼承于 Node 類型的節(jié)點(diǎn),因此擁有 Node 類型上的一些方法。
DOM1 級(jí)定義了一個(gè) Node 接口,該接口將由 DOM 中所有的節(jié)點(diǎn)實(shí)現(xiàn)。
JavaScript 中所有的節(jié)點(diǎn)類型都繼承自 Node 類型,因此所有節(jié)點(diǎn)類型都共享著相同的基本屬性和方法
以上引用自 《JavaScript 高級(jí)程序設(shè)計(jì)(第三版)》
document instanceof Node // true
document.body instanceof Node // true
Document 類型
JavaScript 通過 Document
類型表示整個(gè)文檔,在瀏覽器中有一個(gè) HTMLDocument
類型,其繼承于 Document
類型。在瀏覽器中存在一個(gè) document
對(duì)象,其是 HTMLDocument
類型的一個(gè)實(shí)例。
document instanceof HTMLDocument // true
document instanceof Document // true
document instanceof Node // true
document instanceof Object // true
在 DOM 樹中,一切元素(文檔、元素節(jié)點(diǎn)、注釋、文本、屬性等等)都是某一個(gè)節(jié)點(diǎn)類型的實(shí)例,這些節(jié)點(diǎn)類型都繼承于 Node 類型,在 HTML 文檔中的一切元素都是對(duì)象。(之前對(duì)這方面沒有多少認(rèn)識(shí),寫 HTML 頁(yè)面時(shí)并沒有意識(shí)到我們加到頁(yè)面上的元素都是一個(gè)個(gè)對(duì)象,看了高程后,對(duì) HTML 頁(yè)面的認(rèn)識(shí)更加深刻了。)
Document 類型的特征
Document 類型有以下特征:
document.nodeType // 9
document.nodeName // "#document"
document.nodeValue // null
document.parentNode // null
document.ownerDocument // null
常用子節(jié)點(diǎn)和特殊集合
為了方便我們對(duì)頁(yè)面上的元素進(jìn)行獲取,Document 類型提供了一些快捷的訪問子節(jié)點(diǎn)和特殊集合的方式:
1.document.documentElement
改子元素指向頁(yè)面上的根元素 <html></html>
document.documentElement === document.firstElementChild // true
2.document.body
改子元素指向 <body></body>
3.document.title
可以用來獲取/設(shè)置頁(yè)面的 Title:
document.title = "我要吃烙餅"
document.title // "我要吃烙餅"
4.document.images
該屬性是一個(gè) HTMLCollection,包含了頁(yè)面中的所有 <img />
:
document.images.length // 5
document.getElementsByTagName("img").length // 5
document.images[1] === document.getElementsByTagName("img")[1] // true
5.document.forms
該屬性是一個(gè)包含了頁(yè)面上所有 form
元素的集合。
6.document.links
該屬性是一個(gè)包含了頁(yè)面上所有帶 href
屬性的 a
元素集合。
HTML:
<a href="">1</a>
<a href="">2</a>
<a href="">3</a>
<a href="">4</a>
<a>5</a>
獲取 document.links:
document.links.length // 4
document.write() 和 document.writeln()
docuemtn.write()
和 document.writeln()
方法用來向頁(yè)面中寫入內(nèi)容,通常用來在頁(yè)面加載過程中進(jìn)行內(nèi)容寫入,如果頁(yè)面已經(jīng)加載完成了,調(diào)用 document.write()
或 document.writeln()
方法會(huì)先清空頁(yè)面中的容,再進(jìn)行寫入。
Element 類型
Element 用于表現(xiàn) XML 或者 HTML 中的元素節(jié)點(diǎn),具有以下特征:
- nodeType 的值為 1
- nodeName 的值為元素的標(biāo)簽名
- tagName 的值也是元素的標(biāo)簽名,其值和 nodeName 一樣
- nodeValue 為 null
總結(jié)
HMTL 中有各式各樣的元素,每種元素都是一種節(jié)點(diǎn),它們是某個(gè)節(jié)點(diǎn)類型的實(shí)例(如 HTMLDocument,Element)等,這些節(jié)點(diǎn)類型都繼承于 Node。
HTML 中還有其他類型的節(jié)點(diǎn),如 Text、Attr、Comment 等,這些節(jié)點(diǎn)都有各自相應(yīng)的操作方法和特性,本文主要介紹了最常用的 Document 和 Element 節(jié)點(diǎn),對(duì)于其他節(jié)點(diǎn)類型的操作可以查閱相關(guān)的文檔,在高程這本書中也有比較詳細(xì)的介紹。
完。