Though insertBefore() is great and referenced by most answers here. For added flexibility, and to be a little more explicit, you can use:
The insertAdjacentElement() as refElem.insertAdjacentElement(position, newElem)
lets you reference any element, and insert the to-be moved element exactly where you want (position can be one of: 'beforebegin'
, 'afterbegin'
, 'beforeend'
, 'afterend'
) as shown below:
// refElem.insertAdjacentElement('beforebegin', myElem);
<p id="refElem">
// refElem.insertAdjacentElement('afterbegin', myElem);
... content ...
// refElem.insertAdjacentElement('beforeend', myElem);
</p>
// refElem.insertAdjacentElement('afterend', myElem);
Others to consider for similar use cases: insertAdjacentHTML()
and insertAdjacentText()
References:
https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentElement https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTML https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentText