MDN’s new design is in Beta! A sneak peek:


翻譯不完整。請協助 翻譯此英文文件

Node.childNodes 唯讀屬性會回傳一個即時更新的動態集合(live collection),其包含了指定元素的子節點,而第一個子節點會被指派為索引 0。


var ndList = elementNodeReference.childNodes; 

ndList 是一個 NodeList,為一個有順序性、由目前元素之 DOM 子節點組成之集合。假如目前元素沒有子節點,則 ndList 會是空的。


// parg is an object reference to a <p> element

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

  for (var i = 0; i < children.length; i++) {
    // do something with each child as children[i]
    // NOTE: List is live, adding or removing children will change the list

// 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


The items in the collection of nodes are objects and not strings. To get data from node objects, use their properties (e.g. elementNodeReference.childNodes[1].nodeName to get the name, etc.).

The document object itself has 2 children: the Doctype declaration and the root element, typically referred to as documentElement. (In (X)HTML documents this is the HTML element.)

childNodes includes all child nodes, including non-element nodes like text and comment nodes. To get a collection of only elements, use ParentNode.children instead.




 此頁面的貢獻者: jackblackevo
 最近更新: jackblackevo,