Insert an Element Before Another

To insert an element before an existing element, you use the following helper function:

function insertBefore(newNode, existingNode) {
    existingNode.parentNode.insertBefore(newNode, existingNode);
}

The insertBefore() function selects the parent element of the existing node and calls the insertBefore() method to insert the new node before the existing node.

Was this helpful?