How to capture the innerHTML of a documentFragment via Javascript?

2
The documentFragment that is created using the document.createDocumentFragment() method does not contain the innerHTML and outerHTML equal properties derived from HTMLElement tem.

But I need to get the contents of the snippet in string format. But I can not just give a% of the fragment in another element to have appendChild , as this would leave the instance of the fragment empty once its content would be transported to another element.

I need to extract the string-like HTML from the snippet without changing it.

    
asked by anonymous 25.02.2014 / 21:31

3 answers

2

Use only: frag.querySelector('*').innerHTML

The asterisk selects any first DOM object found inside the fragment, which in the case is the root, and then with the root DOM object in the hands it is possible to use innerHTML , or outerHTML if applicable.

EDIT

If your fragment contains multiple root elements, then use querySelectorAll :

var conteudo = "";
var all = frag.querySelectorAll('*');
    for (var i = 0; i < all.length; i++)
        if (!all[i].parentElement)
            conteudo += all[i].outerHTML;

// mostrando o output na página
$("#output").text($("#output").text() + conteudo);

querySelectorAll is well supported in browsers: link

EDIT 2: A more performative solution using querySelector instead of querySelectorAll :

var conteudo = "";
var current = frag.querySelector('*');
while (current) {
    conteudo += current.outerHTML + "\n";
    current = current.nextSibling;
}

EDIT 3: As the previous options did not work in IE8, I kept searching until I found the following alternative (which works on all browsers I've tested):

var conteudo = "";
var rootNodes = frag.childNodes;
for (var i = 0; i < rootNodes.length; i++)
    conteudo += rootNodes[i].outerHTML;
    
25.02.2014 / 21:53
1

Given its requirements, it seems the only way would be to clone each child's fragment:

function fragHtml(frag) {
    var div = document.createElement('div');
    for(var i=0; i<frag.children.length; i++) {
        div.appendChild(frag.children[i].cloneNode(true));
    }
    return div.innerHTML;
}
    
25.02.2014 / 21:36
1

MDN method:

  

element = documentframgment.querySelector (selectors);

So, an example would be:

HTML

<div id="test" contenteditable="true">
    Teste
    <img src="/favicon.png" alt=""/>
</div>

JS

var frag = document.createDocumentFragment();
var teste = document.getElementById('test');
frag.appendChild(teste);
console.log(frag);       // #document-fragment
var conteudo = frag.querySelector('#test');
console.log(conteudo.innerHTML);   //  Teste<img src="/favicon.png" alt="">

Example

    
25.02.2014 / 21:39