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

前端 未结 2 1441
梦如初夏
梦如初夏 2020-12-30 21:36

Note: I do NOT want to use any framework.


The goal is just to create a function that will return an element based on an HTML string.

2条回答
  •  悲&欢浪女
    2020-12-30 22:01

    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;
    }
    

提交回复
热议问题