JavaScript DOM API doesn’t directly support insert an element after an existing element.
To insert an element after an existing element in the DOM tree, you follow these steps:
- First, select the parent node of the existing element.
- Then, insert the new element before (insertBefore()) the next sibling (nextSibling) of the existing element.
The following helper function allows you to insert an element after an existing element:
function insertAfter(newNode, existingNode) {
existingNode.parentNode.insertBefore(newNode, existingNode.nextSibling);
}
Code language: JavaScript (javascript)
Was this tutorial helpful ?