Use Element.insertAdjacentHTML()
with a position of 'beforebegin'
to parse an HTML string (htmlString
) and insert it before the start of el
.
const insertBefore = (el, htmlString) =>
el.insertAdjacentHTML('beforebegin', htmlString);
// Example
insertBefore(document.getElementById('myId'), '<p>before</p>');
// <p>before</p> <div id="myId">...</div>