Inserting arbitrary HTML into a DocumentFragment

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

    @PAEz pointed out that @RobW's approach does not include text between elements. That's because children only grabs Elements, and not Nodes. A more robust approach might be as follows:

    var fragment = document.createDocumentFragment(),
        intermediateContainer = document.createElement('div');
    
    intermediateContainer.innerHTML = "Wubba
    Lubba
    DubDub"; while (intermediateContainer.childNodes.length > 0) { fragment.appendChild(intermediateContainer.childNodes[0]); }

    Performance may suffer on larger chunks of HTML, however, it is compatible with many older browsers, and concise.

提交回复
热议问题