Inserting arbitrary HTML into a DocumentFragment

前端 未结 11 2135
花落未央
花落未央 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:01

    Like @dandavis said, there is a standard way by using the template-tag.
    But if you like to support IE11 and you need to parse table elements like 'test', you can use this function:

    function createFragment(html){
        var tmpl = document.createElement('template');
        tmpl.innerHTML = html;
        if (tmpl.content == void 0){ // ie11
            var fragment = document.createDocumentFragment();
            var isTableEl = /^[^\S]*?<(t(?:head|body|foot|r|d|h))/i.test(html);
            tmpl.innerHTML = isTableEl ? ''+html : html;
            var els        = isTableEl ? tmpl.querySelector(RegExp.$1).parentNode.childNodes : tmpl.childNodes;
            while(els[0]) fragment.appendChild(els[0]);
            return fragment;
        }
        return tmpl.content;
    }
    

    提交回复
    热议问题