Inserting arbitrary HTML into a DocumentFragment

前端 未结 11 2121
花落未央
花落未央 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条回答
  •  旧时难觅i
    2020-11-29 19:24

    createDocumentFragment creates an empty DOM "container". innerHtml and other methods work only on DOM nodes (not the container) so you have to create your nodes first and then add them to the fragment. You can do it using a painful method of appendChild or you can create one node and modify it's innerHtml and add it to your fragment.

    var frag = document.createDocumentFragment();
        var html = '
    x
    y'; var holder = document.createElement("div") holder.innerHTML = html frag.appendChild(holder)

    with jquery you simply keep and build your html as a string. If you want to convert it to a jquery object to perform jquery like operations on it simply do $(html) which creates a jquery object in memory. Once you are ready to append it you simply append it to an existing element on a page

提交回复
热议问题