Create node from markup string

前端 未结 3 461
心在旅途
心在旅途 2021-01-12 22:30

Is there a way to convert markup string to node object in JavaScript? Actually I am looking for the subsitute for:

document.getElementById(\"divOne\").innerH         


        
相关标签:
3条回答
  • 2021-01-12 23:00
    function htmlMarkupToNode(html){
        let template = document.createElement("template");        
        template.innerHTML = html ;
        let node = template.content.cloneNode(true) ;        
        return node ;   
    }
    
    document.getElementById("divOne").appendChild(htmlMarkupToNode("<table><tbody><tr><td><input type='text' value='0' /></td></tr></tbody></table>"));
    
    0 讨论(0)
  • 2021-01-12 23:13

    There's not an existing cross-browser function for this. The following method can be used to achieve the desired effect (using a DocumentFragment for an optimized performance, based on this answer):

    function appendStringAsNodes(element, html) {
        var frag = document.createDocumentFragment(),
            tmp = document.createElement('body'), child;
        tmp.innerHTML = html;
        // Append elements in a loop to a DocumentFragment, so that the browser does
        // not re-render the document for each node
        while (child = tmp.firstChild) {
            frag.appendChild(child);
        }
        element.appendChild(frag); // Now, append all elements at once
        frag = tmp = null;
    }
    

    Usage (indention for readability):

    appendStringAsNodes(
        document.getElementById("divOne"),
       "<table><tbody><tr><td><input type='text' value='0' /></td></tr></tbody></table>"
    );
    
    0 讨论(0)
  • 2021-01-12 23:23

    Yes, you can do that.

    var myNewTable = document.createElement("table");
    myNewTable.innerHTML = "<tbody><tr><td><input type='text' value='0' /></td></tr></tbody>"
    document.getElementById("divOne").appendChild(myNewTable);
    
    0 讨论(0)
提交回复
热议问题