Search code examples
javascripthtmldom

How to insert HTML string in between two DOM nodes?


Consider following DOM fragment:

<div id="div-1">foo</div>
<div id="div-2">bar</div>

Is it possible to insert HTML string (EDIT: that contains tags to render) between divs without wrapping it in another div (EDIT: or some other tag) created via document.createElement and setting its innerHTML property?


Solution

  • Most browsers support element#insertAdjacentHTML(), which finally became standard in the HTML5 specification. Unfortunately, Firefox 7 and lower don't support it, but I managed to find a workaround that uses ranges to insert the HTML. I've adapted it below to work for your scenario:

    var el = document.getElementById("div-2"),
        html = "<span>Some HTML <b>here</b></span>";
    
    // Internet Explorer, Opera, Chrome, Firefox 8+ and Safari
    if (el.insertAdjacentHTML)
        el.insertAdjacentHTML ("beforebegin", html);
    else {
        var range = document.createRange();
        var frag = range.createContextualFragment(html);
        el.parentNode.insertBefore(frag, el);
    }
    

    Live example: http://jsfiddle.net/AndyE/jARTf/

    Browser Support: https://caniuse.com/insertadjacenthtml