How to correctly use innerHTML to create an element (with possible children) from a html string?

This is similar to the answer from palswim, except that it doesn’t bother with creating a clone, and uses a while() loop instead, always appending the node at [0].

function createElement( str ) {
    var frag = document.createDocumentFragment();

    var elem = document.createElement('div');
    elem.innerHTML = str;

    while (elem.childNodes[0]) {
        frag.appendChild(elem.childNodes[0]);
    }
    return frag;
}

Leave a Comment

tech