var fragment = [];
function create1() {
for (var i = 0; i < 5; i++) {
x = document.createElement('div');
x.className = "di";
x.textContent = 'Change background color';
fragment[i] = document.createDocumentFragment();
console.log(fragment[i]);
fragment[i].append(x.cloneNode(true));
}
document.body.append(fragment);
}
create1();
.di {
border: solid green 2px;
margin-right: 65em;
margin-top: 4px;
}
I created an array of document fragment but I am unable to render them to the HTML DOM properly, please help
3
Answers
Your
fragment
variable is an array, not a document node. You must spread the argument in theappend
call –But don’t stop there –
❌ leaked global variable
x
❌ unnecessary global
fragment
❌ functions don’t take arguments or return values
❌ poor function composition, separate concerns
I agree with @EmielZuurbier. It doesn’t make sense to use fragments that contain a single child. It would be better to either append each
div
to the body directly or append all divs to a fragment and finally append the single fragment to the body. Here’s what that would look like –It doesn’t make a lot of sense to create a
DocumentFragment
per element: aDocumentFragment
can be very useful to collect multiple elements into a single group to append them all at once. Otherwise you could just append the element to the body directly without using the document fragment and get the same result. See the result below.I’m not sure you’ll need an array here. Here’s a utility function creating and appending[n]
elements (using a shorter syntax for element creation) todocument.body
.