# Day JavaScript NodeList vs HTMLCollection - 差異點: 節點的類型不一樣。 - NodeList:包含多種節點,如:元素節點、文字節點、屬性節點、註解節點等節點。 - HTMLCollection:只包含元素節點。 - 相同點: - 都有 .length 屬性可計算長度。 - 都是類陣列。 ## NodeList: 是節點(node)的集合,長的很像陣列,但實質上不是陣列。 NodeList可以使用的方法可參考[mdn NodeList](https://developer.mozilla.org/en-US/docs/Web/API/NodeList)。 ### 節點: 就是 DOM [註1] 裡面的各個物件,主要有以下幾種類型: - 元素節點:HTML 的標籤。 - 文字節點:標籤內的文字內容。 - 屬性節點:標籤內的屬性。 - 註解節點:我們平常用 Ctrl + / 做的註解。 其他節點可參考:[mdn Node.nodeType](https://developer.mozilla.org/zh-TW/docs/Web/API/Node/nodeType) 註1:DOM 是用來把 HTML 文件的標籤變成物件,且存取後拿來使用。 ### 回傳值: 透過 Node.childNodes 跟 document.querySelectorAll()會根據被選取到的對象有哪些節點,回傳對象的 NodeList,也就是回傳對象的節點。 - Node.childNodes:回傳目標對象的動態(live)[註1]子層節點,包括元素節點、文字節點及註解節點。 - document.querySelectorAll():依據選取器選到的節點回傳靜態(static)[註2]節點,除了元素節點、文字節點、註解節點也包括屬性節點及其他節點。 註1:動態代表除了原本 HTML 內有的節點外,如果有使用到 JS 去新增或刪除節點,也會同步抓取。 註2:靜態代表只會抓到原本 HTML 內有的節點。 ## HTMLCollection: 是元素(elements)的集合,類似 arguments 物件的樣子。 HTMLCollection可以使用的方法可參考[mdn HTMLCollection](https://developer.mozilla.org/en-US/docs/Web/API/HTMLCollection)。 透過 getElementsByClassName() 跟 getElementsByTagName()會根據被選取到的對象有哪些元素節點,回傳對象的 HTMLCollection。 --- ### 參考資料: [重新認識 JavaScript: Day 12 透過 DOM API 查找節點](https://ithelp.ithome.com.tw/articles/10191765) [mdn NodeList](https://developer.mozilla.org/en-US/docs/Web/API/NodeList) [mdn Node.nodeType](https://developer.mozilla.org/zh-TW/docs/Web/API/Node/nodeType) [mdn HTMLCollection](https://developer.mozilla.org/en-US/docs/Web/API/HTMLCollection) --- ###### tags: `13th鐵人賽` `網頁前後端寶石庫-礦坑補完計畫`
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up