How To Correctly Use Innerhtml To Create An Element (with Possible Children) From A Html String?
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. Assume a simple HTML Document like such: <
Solution 1:
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]
.
functioncreateElement( str ) {
var frag = document.createDocumentFragment();
var elem = document.createElement('div');
elem.innerHTML = str;
while (elem.childNodes[0]) {
frag.appendChild(elem.childNodes[0]);
}
return frag;
}
Solution 2:
You'd have to attach the new element somewhere. Try using a DocumentFragment
object in conjunction with the div
you created:
functioncreateElement(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).
Post a Comment for "How To Correctly Use Innerhtml To Create An Element (with Possible Children) From A Html String?"