How to convert from mixed HTML-string/DOM-elements to DOM-elements in Javascript? -
i wish implement following javascript function:
function alltodom(partsarray) {     // magic! }  // called like: var rowobject = alltodom(['<tr>', tdelem1, tdelem2, '<td>xxx</td>', '<td>',      divcontents,'</td></tr>']);  // tdelem1, tdelem2, divcontents dom node objects. the thing want work on kinds of combinations of dom nodes , html fragments. long produces valid html of course. unclosed html tags , disallowed element combinations (like <table><div></div>) allowed have undefined behavior.
my first idea concatenate in html string, except in place of dom elements add placeholder comment <!--snoopy-->. above result in following string:
<tr><!--snoopy--><!--snoopy--><td>xxx</td><td><!--snoopy--></td></tr> this valid piece of html, next create <div>, assign innerhtml, gather produced dom nodes, , iterate through them , replace <!--snoopy--> respective dom element.
there 2 flaws approach however:
- adding <tr>child element<div>invalid. don't know if might not break on condition.
- internet explorer 8 (the least version need support) strips comments when assigning innerhtml.
are there workarounds? possible @ all?
finally found answer: jquery has done dirty work in parsehtml() method. , happen using jquery anyway, me! :)
i checked magic behind scenes, , it's pretty gruesome. first, inspect html (with regexs...) see parent tag need use, , have workaround ie8, apparently preserve comment nodes - if come after text node. comments before first text node lost. , tags affected way too, had no idea about. , there's half dozen other workarounds ie & webkit problems i've never heard of.
so, i'm going leave them right thing, because trying reproduce stuff madness.
Comments
Post a Comment