Inserting a nested div structure with createDocumentFragment

后端 未结 2 939
迷失自我
迷失自我 2020-12-11 21:02

How do you use createDocumentFragment to create seven nested div elements in one hit?

I want to create a container A which contains A1, A2, A3 & A4, and then A2a

2条回答
  •  萌比男神i
    2020-12-11 21:58

    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.

提交回复
热议问题