Inserting arbitrary HTML into a DocumentFragment

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

    Currently, the only way to fill a document fragment using only a string is to create a temporary object, and loop through the children to append them to the fragment.

    • Since it's not appended to the document, nothing is rendered, so there's no performance hit.
    • You see a loop, but it's only looping through the first childs. Most documents have only a few semi-root elements, so that's not a big deal either.

    If you want to create a whole document, use the DOMParser instead. Have a look at this answer.

    Code:

    var frag = document.createDocumentFragment(),
        tmp = document.createElement('body'), child;
    tmp.innerHTML = '
    x
    y'; while (child = tmp.firstElementChild) { frag.appendChild(child); }

    A one-liner (two lines for readability) (input: String html, output: DocumentFragment frag):

    var frag =document.createDocumentFragment(), t=document.createElement('body'), c;
    t.innerHTML = html; while(c=t.firstElementChild) frag.appendChild(c);
    

提交回复
热议问题