Use only: frag.querySelector('*').innerHTML
The asterisk selects any first DOM object found within the fragment, which in this case is the root, and then with the root DOM object in the hands it is possible to use innerHTML
, or the outerHTML
if applicable.
EDIT
In case 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:
http://caniuse.com/queryselector
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: since the previous options didn’t work in IE8, I kept looking until I found the following alternative (which works on all browsers I tested):
var conteudo = "";
var rootNodes = frag.childNodes;
for (var i = 0; i < rootNodes.length; i++)
conteudo += rootNodes[i].outerHTML;
I updated the answer to multiple root elements.
– Miguel Angelo
querySelectorAll
guarantees the order of the elements? If it guarantees probably this solution this solution serves my purpose.– Gabriel Gartz
Gosh, he’s also selecting the children... I’ll see if there’s only the root elements without the children.
– Miguel Angelo
Miguel I think that to join your answer with bfavaretto, would be the most correct solution, now I do not know who to give as solution to the question...
– Gabriel Gartz
I think that
querySelectorAll('*')
will catch all the elements inside the Fragment, not just the roots.– bfavaretto
Corrected code, now only the roots will be selected.
– Miguel Angelo
I deleted the non-roots manually, inside the for... I don’t know if this is good for performance.
– Miguel Angelo
Now yes, a solution that is not bad performance: use
querySelector('*')
and then usenextSibling
and concatenate the outerHTML. This way, even, the ordering is more guaranteed... is the order of insertion of the elements in the fragment.– Miguel Angelo
Thousandth edition... =) It was bad for so many personal editions.
– Miguel Angelo
Thanks Miguel, really the last was the same thing I ended up doing to solve this case, so the answer is correct, the cool of the issues is that there is a knowledge base for the next ones who have this same doubt. = ) Thank you again!
– Gabriel Gartz
Edit 2 is very efficient, 3x faster than mine: http://jsperf.com/documentfragment-innerhtml
– bfavaretto