1

I creating a function in angular 2 that converts from html string to Documents fragment:

 private htmlToElement(html): DocumentFragment {
    let template = document.createElement('template');
    html = html.trim(); // Never return a text node of whitespace as the result
    template.innerHTML = html;
    return template.content;
  }

It works for Chrome and Firefox, but for IE11, throws the following error ERROR TypeError: Object doesn't support property or method 'getElementById'. I investigated it and it seems that template.content is undefined. Is there a workaround to make it work also in IE11? Thanks!

Denisa Corbu
  • 301
  • 2
  • 16

1 Answers1

0

You could use one of the many polyfill options, a mininal solution could be https://www.npmjs.com/package/template-polyfill or a more complex implementation https://github.com/webcomponents/polyfills/blob/master/packages/template/template.js

Or you could use the following code, which is for sure longer, not complete, but not really slower and the principle should help you solve your issue:

/**
 * Convert string to html
 *
 * @param {string} str - HTML source string
 * @param {boolean} multiple - Contains multiple nodes, default: true
 *
 * @return {null|HTMLElement|NodeList} - Element or collection of elements
 */
export function str2node( str, multiple = true ) {
    str = str.trim();
    if ( !str.length ) {
        return null;
    }

    /**
     * Best practice should be the following, once IE11 support dies, or when using a polyfill
     */
    let template = document.createElement( 'template' );
    if ( 'content' in template ) {
        template.innerHTML = str;
        if ( multiple ) {
            return template.content.childNodes;
        }
        return template.content.firstChild;
    }

    // fix for IE11, with slow detection using div or correct parent element if required
    // TODO: check for other special cases with elements requiring a specific parent?
    // like: source [ audio video picture ], area [ map ], caption [ table ], option [ select],
    // td > tr > table tbody tfoot thead, dt dd > dl
    template = document.createElement( str.substr( 0, 4 ) === '<li ' ? 'ul' : 'div' );
    template.innerHTML = str;
    if ( multiple ) {
        return template.childNodes;
    }
    return template.firstChild;
}
siux
  • 21
  • 3