javascripthtmlinsertadjacenthtml

How to insertAdjacentHTML between 2 different divs


I need to get my div between 2 divs inside my template. I can only edit it with external HTML, JS. Template looks like this:

<main id="content-in">
    <div id="homepage-banner"> XXX </div>
    <div id="carousel-banner"> XXX </div>

And I need to get my img and a href <div id="moveOut"> XXX </div> between these 2.

I have it like this now which works ok:

<script>
function addCode() {
    var d1 = document.getElementById('content-in');
    d1.insertAdjacentHTML('afterbegin', '<div id="moveOut"><a href="https://example.com/"><img src="https://example.png" alt=""></a></div>');
        }
</script>

but I need to move it. Thank you for your help.


Solution

  • You need to insert after the homepage-banner DIV.

    var d1 = document.getElementById("homepage-banner");
    d1.insertAdjacentHTML('afterend', '<div id="moveOut"><a href="https://example.com/"><img src="https://example.png" alt=""></a></div>');