Inserting a nested div structure with createDocumentFragment

末鹿安然 提交于 2019-11-28 13:54:08

Rather than calling appendChild on the fragment (which creates a top level object in your fragment), you call appendChild on one of the other objects in your fragment and that nests into that object. Here's a pseudo code example that puts tag2 nested into tag.

var tag = document.createElement(tag);
tag.id = id;
tag.className = className;
fragment.appendChild(tag); 

var tag2 = document.createElement(tag);
tag2.id = id2;
tag.className = className2;
tag.appendChild(tag2);

Note: you can also set tag.innerHTML and create a whole host of objects (including as many layers of nesting as you want) just from that HTML.

Once I made a recursive function that parsed an JSON object (received from the server) to a DocumentFragment. I need to dig it out again. Here is a JSON of that kind. Recursion start on 'children':

var input="query":"#toPasteId","child":{"#toPasteId":{"a":"div","style":"color:blue","children":[{"a":"span","textcontent":"blabla"},{"a":"div","style":"border: 5px solid red","textcontent":"blublub"}]}}

It might not help but probably you'll find out before I find my paddle.

PS:Found it.

,oParse=function(obj){
        var query=obj.query
           ,curObj=obj.child
           ,frag=document.createDocumentFragment()
           ,d=document
           ,rParse=function(curObj,frag){
                   var curElem=d.createElement(curObj.a);
                   frag.appendChild(curElem);
                   delete curObj.a;
                   for(var elem in curObj){
                        switch(elem){
                              case 'child':
                                   if(curObj.child.length){
                                     for(var i=0;i<curObj.child.length;i++){
                                        rParse(curObj.child[i],curElem);
                                     }
                                   }                                
                                   else{
                                     rParse(curObj.child,curElem);
                                   }
                                   break;
                              case 'style':  
                                   curElem.style.cssText=curObj[elem];                                             
                                   break;   
                              default:
                                   curElem[elem]=curObj[elem];
                    }      
                 }  
           return frag;
           };

d.querySelector(query).appendChild(rParse(curObj,frag));
};

oParse(input);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!