首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >IE11文档片段

IE11文档片段
EN

Stack Overflow用户
提问于 2018-02-26 22:59:40
回答 1查看 815关注 0票数 1

我在angular 2中创建了一个将html字符串转换为文档片段的函数:

代码语言:javascript
复制
 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;
  }

它适用于Chrome和Firefox,但对于IE11,抛出以下错误错误TypeError: Object不支持属性或方法'getElementById‘。我调查了一下,template.content似乎是未定义的。有没有办法让它在IE11中也能工作?谢谢!

EN

回答 1

Stack Overflow用户

发布于 2021-03-22 21:55:39

您可以使用许多polyfill选项中的一个,最小的解决方案可以是https://www.npmjs.com/package/template-polyfill或更复杂的实现https://github.com/webcomponents/polyfills/blob/master/packages/template/template.js

或者你可以使用下面的代码,它肯定更长,不完整,但也不是很慢,原理应该能帮助你解决问题:

代码语言:javascript
复制
/**
 * 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;
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48991350

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档