Inserting arbitrary HTML into a DocumentFragment

前端 未结 11 2133
花落未央
花落未央 2020-11-29 18:53

I know that adding innerHTML to document fragments has been recently discussed, and will hopefully see inclusion in the DOM Standard. But, what is the workaround you\'re sup

11条回答
  •  余生分开走
    2020-11-29 19:05

    Here is a way in modern browsers without looping:

    var temp = document.createElement('template');
    temp.innerHTML = '
    x
    y'; var frag = temp.content;

    or, as a re-usable

    function fragmentFromString(strHTML) {
        var temp = document.createElement('template');
        temp.innerHTML = strHTML;
        return temp.content;
    }
    

    UPDATE: I found a simpler way to use Pete's main idea, which adds IE11 to the mix:

    function fragmentFromString(strHTML) {
        return document.createRange().createContextualFragment(strHTML);
    }
    

    The coverage is better than the