Node.firstChild
read-only property returns the node's first child in the tree, or
null
if the node has no children.
若节点是
Document
, it returns the first node in the list of its direct children.
var childNode = node.firstChild;
This example demonstrates the use of
firstChild
and how whitespace nodes might interfere with using this property.
<p id="para-01">
<span>First span</span>
</p>
<script>
var p01 = document.getElementById('para-01');
console.log(p01.firstChild.nodeName);
</script>
In the above, the
console
will show '#text' because a text node is inserted to maintain the whitespace between the end of the opening
<p>
and
<span>
标签。
任何
whitespace
将创建
#text
node, from a single space to multiple spaces, returns, tabs, and so on.
Another
#text
node is inserted between the closing
</span>
and
</p>
标签。
If this whitespace is removed from the source, the #text nodes are not inserted and the span element becomes the paragraph's first child.
<p id="para-01"><span>First span</span></p>
<script>
var p01 = document.getElementById('para-01');
console.log(p01.firstChild.nodeName);
</script>
Now the console will show 'SPAN'.
To avoid the issue with
node.firstChild
返回
#text
or
#comment
nodes,
ParentNode.firstElementChild
can be used to return only the first element node. However,
node.firstElementChild
requires a shim for Internet Explorer 9 and earlier.
| 桌面 | 移动 | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|
firstChild
|
Chrome Yes | Edge 12 | Firefox 1 | IE Yes | Opera Yes | Safari Yes | WebView Android Yes | Chrome Android Yes | Firefox Android 4 | Opera Android Yes | Safari iOS Yes | Samsung Internet Android Yes |
完整支持
节点
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