Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create node from markup string

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

document.getElementById("divOne").innerHTML += "<table><tbody><tr><td><input type='text' value='0' /></td></tr></tbody></table>"

something like

document.getElementById("divOne").appendChild(document.createNodeFromString("<table><tbody><tr><td><input type='text' value='0' /></td></tr></tbody></table>"))

using createNodeFromString rather creating the table element then append its child elements then attach their respective attributes and values!

like image 737
vulcan raven Avatar asked Feb 17 '12 20:02

vulcan raven


2 Answers

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>"
);
like image 75
Rob W Avatar answered Oct 06 '22 06:10

Rob W


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);
like image 33
caleb Avatar answered Oct 06 '22 06:10

caleb