Skip to main content

Tedshd's Dev note

JavaScript - insertBefore & insertAfter

Table of Contents

# JavaScript - insertBefore & insertAfter

## insertBefore

This is native JavaScript api

var insertedElement = parentElement.insertBefore(newElement, referenceElement);

var vDom = document.createElement('div'),
    dom = document.querySelector('#list');
dom.insertBefore(vDom, dom.childNodes[1]);

// or

var vDom = document.createElement('div'),
    dom = document.querySelector('#target');
dom.parentNode.insertBefore(vDom, dom);

Refer - Node.insertBefore()

## insertAfter

JavaScript doesn’t have any api handle insert DOM after reference DOM

We can use this way

function insertAfter(newNode, referenceNode) {
    referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
}

Refer - How to do insert After() in JavaScript without using a library?