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

前端 未结 2 1440
梦如初夏
梦如初夏 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;
    }
    
    0 讨论(0)
  • 2020-12-30 22:06

    You'd have to attach the new element somewhere. Try using a DocumentFragment object in conjunction with the div you created:

    function createElement(str) {
        var div = document.createElement('div');
        div.innerHTML = str;
        var container = document.createDocumentFragment();
        for (var i=0; i < div.childNodes.length; i++) {
            var node = div.childNodes[i].cloneNode(true);
            container.appendChild(node);
        }
        return container.childNodes;
    }
    

    It's more overhead, but it does what you want. Note that DOM elements' .insertAdjacentHTML member function is coming in HTML5.

    For that complex string you passed, it isn't valid XHTML syntax - you can't have a block element as a child of <p> (<h2> is a block level element).

    0 讨论(0)
提交回复
热议问题