the murmurous sea

HTML DOM: insertBefore() 본문

#dev/개념정리

HTML DOM: insertBefore()

lunacer 2020. 5. 2. 12:04

1. method 
2. inserts a node before a reference node as a child of a specified parent node.
3. use the insertBefore method to insert/move an existing element.
3. a node cannot be in two locations of the document simultaneously.
   : 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.)
4. If the given child is a DocumentFragment, the entire contents of the DocumentFragment are moved into the child list.

 

[Syntax]

let insertedNode = parentNode.insertBefore(newNode, referenceNode)
insertedNode   The node being inserted (the same as newNode)
parentNode   The parent of the newly inserted node.
newNode Required The node object you want to insert.
referenceNode Required
The child node you want to insert the new node before.
If this is null, then newNode is inserted at the end of parentNode's child nodes.
It's not an optional parameter. Must explicitly pass a Node or null.

[Return value]

The added child A Node Object, representing the inserted node.
: unless newNode is a DocumentFragment, in which case the empty DocumentFragment is returned.

 

 

[insertAfter()]

There is no insertAfter() method. It can be emulated by combining the insertBefore method with Node.nextSibling.

In this example, sp1 could be inserted after sp2 using:

parentDiv.insertBefore(sp1, sp2.nextSibling)

If sp2 does not have a next sibling, then it must be the last child.
: sp2.nextSibling returns null, and sp1 is inserted at the end of the child node list (immediately after sp2).


https://developer.mozilla.org/en-US/docs/Web/API/Node/insertBefore

https://www.w3schools.com/jsref/met_node_insertbefore.asp

 

Comments