Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
697 views
in Technique[技术] by (71.8m points)

javascript - Inserting a nested div structure with createDocumentFragment

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 & A2b within A2.

Note: this is a follow-up question to this which explained createDocumentFragment, but not how to nest divs using it. The answer given was as follows (which was helpful as far as it went):

var fragment = document.createDocumentFragment();

function u1(tag, id, className){
    var tag = document.createElement(tag);
    tag.id = id;
    tag.className = className;
    fragment.appendChild(tag); 
}

// call u1() seven times

document.getElementById('foo').appendChild(fragment);

Could someone explain how to nest? The above just adds seven children to 'foo'. I've trawled the web, but to no avail.

Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...