Namespace: Elements:insertNode

Elements:insertNode

Methods

insertNode(target, node, positionopt, nullable) → {HTMLElement}

Inserts a node into the DOM in relation to a target element.

If the node is not an element, the parameter is treated as source and a node is created automatically based on that.

The position can be determined with the same values as in "insertAdjacentElement" (see: https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentElement), but we also added the more intuitive jQuery aliases for positions:

  • "beforebegin" can also be described as "before"
  • "afterbegin" can also be described as "prepend"
  • "beforeend" can also be described as "append"
  • "afterend" can also be descrived as "after"
Parameters:
Name Type Attributes Default Description
target HTMLElement

the element to which the node will be inserted in relation to

node HTMLElement | String

the node to insert, either as element or source string

position String <optional>
<nullable>
'beforeend'

the position to insert the node in relation to target, the default value appends the node as the last child in target

Source:
Throws:

error if target is not an HTMLElement

Returns:
the inserted DOM-node
Type
HTMLElement
Example
insertNode(document.querySelector('.list-container'), listItemElement);
insertNode(document.querySelector('.list-container'), '<li>Item 42</li>', 'prepend');