Node: childNodes 屬性

Baseline 已廣泛支援

此特性已相當成熟,可在許多裝置和瀏覽器版本上使用。自 ⁨2015 年 7 月⁩以來,各瀏覽器均已提供此特性。

Node 介面的只讀 childNodes 屬性返回一個即時的 NodeList,其中包含給定元素的子 節點,第一個子節點索引為 0。子節點包括元素、文字和註釋。

注意: 即時 NodeList 意味著每次新增或刪除新子節點時,其內容都會發生更改。

瀏覽器會將文字節點插入文件以表示原始碼標記中的空格。因此,例如使用 Node.childNodes[0] 獲取的節點可能指向一個空格文字節點,而不是作者 intended 獲取的實際元素。

有關更多資訊,請參閱 DOM 中的空格處理

集合中的節點是物件,而不是字串。要從節點物件獲取資料,請使用它們的屬性。例如,要獲取第一個 childNode 的名稱,可以使用 elementNodeReference.childNodes[0].nodeName

document 物件本身有兩個子節點:Doctype 宣告和根元素,通常稱為 documentElement。在 HTML 文件中,後者是 <html> 元素。

請記住,childNodes 包括所有子節點,包括非元素節點,如文字和註釋。要獲取僅包含元素的集合,請使用 Element.children

一個包含節點子節點的即時 NodeList

注意:childNodes 的幾次呼叫返回的是同一個 NodeList

示例

簡單用法

js
// Note that para is an object reference to a <p> element

// First check that the element has child nodes
if (para.hasChildNodes()) {
  let children = para.childNodes;

  for (const node of children) {
    // Do something with each child as children[i]
    // NOTE: List is live! Adding or removing children will change the list's `length`
  }
}

移除節點的所有子節點

js
// This is one way to remove all children from a node
// box is an object reference to an element
while (box.firstChild) {
  // The list is LIVE so it will re-index each call
  box.removeChild(box.firstChild);
}

規範

規範
DOM
# ref-for-dom-node-childnodes①

瀏覽器相容性

另見