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);
}Code language: JavaScript (javascript)

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 tutorial helpful ?