Node.childNodes
read-only property returns a live
NodeList
of child
nodes
of the given element where the first child node is assigned index 0.
let nodeList = elementNodeReference.childNodes;
// parg is an object reference to a <p> element
// First check that the element has child nodes
if (parg.hasChildNodes()) {
let children = parg.childNodes;
for (let 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's `length`
}
}
// 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);
}
The items in the collection of nodes are objects, not strings. To get data from node objects, use their properties. (For example, to get the name of the first childNode:
elementNodeReference
.childNodes[1].nodeName
)。
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
包括
all
child nodes—including non-element nodes like text and comment nodes. To get a collection of only elements, use
ParentNode.children
代替。
| 桌面 | 移动 | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|
childNodes
|
Chrome 1 | Edge 12 | Firefox 1 | IE 5 | Opera 7 | Safari 1.2 | WebView Android 1 | Chrome Android 18 | Firefox Android 4 | Opera Android 10.1 | Safari iOS 1 | Samsung Internet Android 1.0 |
完整支持
节点
AbortController
AbortSignal
AbstractRange
Attr
ByteString
CDATASection
CSSPrimitiveValue
CSSValue
CSSValueList
CharacterData
ChildNode
注释
CustomEvent
DOMConfiguration
DOMError
DOMErrorHandler
DOMException
DOMImplementation
DOMImplementationList
DOMImplementationRegistry
DOMImplementationSource
DOMLocator
DOMObject
DOMParser
DOMPoint
DOMPointInit
DOMPointReadOnly
DOMRect
DOMString
DOMTimeStamp
DOMTokenList
DOMUserData
Document
DocumentFragment
DocumentType
元素
ElementTraversal
Entity
EntityReference
事件
EventTarget
HTMLCollection
MutationObserver
NodeFilter
NodeIterator
NodeList
NonDocumentTypeChildNode
ProcessingInstruction
PromiseResolver
范围
StaticRange
文本
TextDecoder
TextEncoder
TimeRanges
TreeWalker
TypeInfo
USVString
UserDataHandler
XMLDocument