dannymcgee
dannymcgee

Reputation: 673

How to return a document fragment as a string of HTML

I'm creating an array of HTML elements.

var elements = [];

Most of these elements are being added to the array as simple strings of HTML, like this:

function myHtml() {
    return '<div>Hi there, here\'s some HTML</div>';
}

elements.push(myHtml());

However, one of these elements is being generated as a document fragment, like this:

function myFragment() {
    var fragment = document.createDocumentFragment();
    var div = document.createElement('div');
    div.appendChild(document.createTextNode('Hi there, here\'s some HTML');
    fragment.appendChild(div);
    return fragment;
}

elements.push(myFragment());

After creating the array, I'm inserting all of the elements into the DOM like this:

function myHtml() {...}
function myFragment() {...}

var elements = [];

elements.push(myHtml(), myFragment());

$('.my-selector').html(elements);

The problem, of course, is that the document fragment doesn't work like that, so it doesn't get inserted into the DOM the way I need it to. The reason I can't just append the fragment to .my-selector the normal way is because I'm generating different arrays based on different conditions, like:

if (condition1) {
    elements.push(myHtml1(), myHtml2(), myFragment());
else {
    elements.push(myHtml3(), myFragment(), myHtml4());
}

$('.my-selector').html(elements);

The order in which the elements appear matters.

I've found a ton of solutions for converting a string of HTML into a document fragment, but no way to convert a document fragment into a string of HTML so that I can use it in this manner. Is it possible? Is there something really simple that I'm missing?

Upvotes: 2

Views: 4458

Answers (1)

chiliNUT
chiliNUT

Reputation: 19573

Append it to an element and get the element's innerHTML

let div=document.createElement("div");
div.appendChild(fragment);
div.innerHTML;

Upvotes: 7

Related Questions