Node.insertBefore()
method inserts a node before a
reference node
as a child of a specified
parent node
.
If the given node already exists in the document,
insertBefore()
moves it from its current position to the new position. (That is, it will automatically be removed from its existing parent before appending it to the specified new parent.)
This means that a node cannot be in two locations of the document simultaneously.
注意:
Node.cloneNode()
can be used to make a copy of the node before appending it under the new parent. Note that the copies made with
cloneNode()
will not be automatically kept in sync.
If the given child is a
DocumentFragment
, the entire contents of the
DocumentFragment
are moved into the child list of the specified parent node.
let insertedNode = parentNode.insertBefore(newNode, referenceNode)
insertedNode
newNode
)
parentNode
The parent of the newly inserted node.
newNode
The node to be inserted.
referenceNode
newNode
is inserted. If this is
null
,那么
newNode
is inserted at the end of
parentNode
's child nodes.
注意:
referenceNode
is
not
an optional parameter. You must explicitly pass a
节点
or
null
. Failing to provide it or passing invalid values may
behave
differently
in different browser versions.
Returns the added child (unless
newNode
是
DocumentFragment
, in which case the empty
DocumentFragment
is returned).
<div id="parentElement">
<span id="childElement">foo bar</span>
</div>
<script>
// Create the new node to insert
let newNode = document.createElement("span")
// Get a reference to the parent node
let parentDiv = document.getElementById("childElement").parentNode
// Begin test case [ 1 ] : Existing childElement (all works correctly)
let sp2 = document.getElementById("childElement")
parentDiv.insertBefore(newNode, sp2)
// End test case [ 1 ]
// Begin test case [ 2 ] : childElement is of Type undefined
let sp2 = undefined // Non-existent node of id "childElement"
parentDiv.insertBefore(newNode, sp2) // Implicit dynamic cast to type Node
// End test case [ 2 ]
// Begin test case [ 3 ] : childElement is of Type "undefined" ( string )
let sp2 = "undefined" // Non-existent node of id "childElement"
parentDiv.insertBefore(newNode, sp2) // Generates "Type Error: Invalid Argument"
// End test case [ 3 ]
</script>
<div id="parentElement">
<span id="childElement">foo bar</span>
</div>
<script>
// Create a new, plain <span> element
let sp1 = document.createElement("span")
// Get the reference element
let sp2 = document.getElementById("childElement")
// Get the parent element
let parentDiv = sp2.parentNode
// Insert the new element into before sp2
parentDiv.insertBefore(sp1, sp2)
</script>
注意:
There is no
insertAfter()
method. It can be emulated by combining the
insertBefore
method with
Node.nextSibling
.
In the previous example,
sp1
could be inserted after
sp2
using:
parentDiv.insertBefore(sp1, sp2.nextSibling)
若
sp2
does not have a next sibling, then it must be the last child —
sp2.nextSibling
返回
null
,和
sp1
is inserted at the end of the child node list (immediately after
sp2
).
Insert an element before the first child element, using the
firstChild
特性。
// Get the parent element
let parentElement = document.getElementById('parentElement')
// Get the parent's first child
let theFirstChild = parentElement.firstChild
// Create a new element
let newElement = document.createElement("div")
// Insert the new element before the first child
parentElement.insertBefore(newElement, theFirstChild)
When the element does not have a first child, then
firstChild
is
null
. The element is still appended to the parent, after the last child.
Since the parent element did not have a first child, it did not have a last child, either. Consequently, the newly inserted element is the only 元素。
| 规范 | 状态 | 注释 |
|---|---|---|
|
DOM
The definition of 'Node.insertBefore' in that specification. |
实时标准 | Fixes errors in the insertion algorithm |
|
DOM4
The definition of 'Node.insertBefore' in that specification. |
过时 | Describes the algorithm in more detail |
|
DOM (文档对象模型) 3 级核心规范
The definition of 'Node.insertBefore' in that specification. |
过时 | No notable changes |
|
DOM (文档对象模型) 级别 2 核心规范
The definition of 'Node.insertBefore' in that specification. |
过时 | No notable changes |
|
DOM (文档对象模型) 1 级规范
The definition of 'Node.insertBefore' in that specification. |
过时 | 引入 |
| 桌面 | 移动 | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|
insertBefore
|
Chrome 1 | Edge 12 | Firefox 3 | IE 9 | Opera 7 | Safari 1.1 | WebView Android 1 | Chrome Android 18 | Firefox Android 4 | Opera Android 10.1 | Safari iOS 1 | Samsung Internet Android 1.0 |
完整支持
Node.removeChild()
Node.replaceChild()
Node.appendChild()
Node.hasChildNodes()
Element.insertAdjacentElement()
ParentNode.prepend()
ChildNode.before()
ChildNode.after()
节点
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