I wish to implement the following Javascript function:
function AllToDom(partsArray)
{
// Magic!
}
// Called like:
var rowObject = AllToDom(['<tr>', tdElem1, tdElem2, '<td>XXX</td>', '<td>',
divContents,'</td></tr>']);
// Where tdElem1, tdElem2, divContents are DOM node objects.
The thing is I want it to work on any kinds of combinations of DOM nodes and HTML fragments. As long as it produces a valid HTML of course. Unclosed HTML tags and disallowed element combinations (like <table><div></div>
) are allowed to have undefined behavior.
My first idea was to concatenate it all in a HTML string, except in place of DOM elements add a placeholder comment <!--SNOOPY-->
. So the above would result in the following string:
<tr><!--SNOOPY--><!--SNOOPY--><td>XXX</td><td><!--SNOOPY--></td></tr>
This is already a valid piece of HTML, so next I create a <div>
, assign this to innerHTML
, gather the produced DOM nodes, and iterate through them and replace all <!--SNOOPY-->
with the respective DOM element.
There are two flaws with this approach however:
- Adding a
<tr>
as a child element to a<div>
is invalid. I don't know if it might not break on some condition. - Internet Explorer 8 (the least version that I need to support) strips all comments when assigning to
innerHTML
.
Are there any workarounds? Is this possible at all?