javascript - Is there any way to create a document fragment from a generic piece of HTML? -
i'm working on application uses client-side templates render data , of javascript template engines return simple string markup , it's developer insert string dom.
i googled around , saw bunch of people suggesting use of empty div, setting innerhtml new string , iterating through child nodes of div so
var parsedtemplate = 'something returned template engine'; var tempdiv = document.createelement('div'), childnode; var documentfragment = document.createdocumentfragment; tempdiv.innerhtml = parsedtemplate; while ( childnode = tempdiv.firstchild ) { documentfragment.appendchild(childnode); }
and tada, documentfragment
contains parsed template. however, if template happens tr
, adding div around doesn't achieve expected behaviour, adds contents of td
's inside row.
does know of way of solve this? right i'm checking node parsed template inserted , creating element tag name. i'm not sure there's way of doing this.
while searching came across this discussion on w3 mailing lists, there no useful solution, unfortunately.
you can use domparser xhtml avoid html "auto-correction" doms perform:
var parser = new domparser(), doc = parser.parsefromstring('<tr><td>something returned </td><td>by template engine</td></tr>', "text/xml"), documentfragment = document.createdocumentfragment() ; documentfragment.appendchild( doc.documentelement ); //fragment populated, view html verify fragment contains what's expected: var temp=document.createelement('div'); temp.appendchild(documentfragment); console.log(temp.outerhtml); // shows: "<div><tr><td>something returned </td><td>by template engine</td></tr></div>"
this contrasted using naive innerhtml temp div:
var temp=document.createelement('div'); temp.innerhtml='<tr><td>something returned </td><td>by template engine</td></tr>'; console.log(temp.outerhtml); // shows: '<div>something returned template engine</div>' (bad)
by treating template xhtml/xml (making sure it's well-formed), can bend normal rules of html. coverage of domparser should correlate support documentfragment, on old copies (single-digit-versions) of firefox, might need use importnode().
as re-usable function:
function strtofrag(strhtml){ var temp=document.createelement('template'); if( temp.content ){ temp.innerhtml=strhtml; return temp.content; } var parser = new domparser(), doc = parser.parsefromstring(strhtml, "text/xml"), documentfragment = document.createdocumentfragment() ; documentfragment.appendchild( doc.documentelement ); return documentfragment; }
Comments
Post a Comment