DEV Community

Cover image for Document Fragments and why you should use them

Document Fragments and why you should use them

Abdulqudus Abubakre on April 10, 2020

A document fragment is a fragment of a Document Object Model (DOM) tree, a chunk of tree that's separated from the rest of the DOM. Before going fu...
Collapse
 
isaachagoel profile image
Isaac Hagoel

Beside the additional div in the Dom tree, what is the different between creating the fragment and creating a div (using createElement) and appending all of the elements to it before finally appending it to the Dom? As long as the parent div is not in the Dom there will be no reflows, right?

Collapse
 
ibn_abubakre profile image
Abdulqudus Abubakre

Well, as you rightly mentioned, there's the fact that you'd be creating an additional element, which might or might not be what you wanted to achieve.
Also when using fragments, the children are effectively moved into the DOM and leaves behind an empty fragment.
But then again, they both serve the same purpose, and whatever works for you is fine. Some people would suggest using the createElement cause it's faster, some would say to use the DocumentFragment cause it was built for this

Collapse
 
yogeshdatir profile image
Yogesh Datir

If this has to be done multiple times, it will only create an untidy DOM tree with lots of empty divs. Then this will affect accessing DOM elements. For the same reason react also introduced Fragments.

Collapse
 
raddevus profile image
raddevus

Thanks for writing this up. It was really great.

This was such a great article that it inspired me to create a simple example CodePen for it.
You can check it out at : codepen.io/raddevus/pen/WNQbOpK
It looks like this:
Country Flags via CodePen

Collapse
 
ibn_abubakre profile image
Abdulqudus Abubakre

This is really amazing. Good work with the display 👌🏻

Collapse
 
sumitsood3127 profile image
sumeet sood

We can store the elements in array and after completing loop call append method with array.
`

`
function getListContent() {
let result = [];

for(let i=1; i<=3; i++) {``
let li = document.createElement('li');
li.append(i);
result.push(li);
}

return result;
}

ul.append(...getListContent()); // append + "..." operator = friends!
``

Collapse
 
aibee profile image
Iboro

Performance is such an important issue so this is just great. I particularly love that the fragment acts as a temporary storage and empties itself automatically after use.

Collapse
 
fleshmecha profile image

This is seriously brilliant. I needed this.

Collapse
 
ibn_abubakre profile image
Abdulqudus Abubakre

Really glad I could be of help

Collapse
 
deven96 profile image
Diretnan Domnan

Pretty neat writeup. I didn't for once consider optimizing for reflow

Collapse
 
ankittanna profile image
Ankit Tanna

Nice one

Collapse
 
ibn_abubakre profile image
Abdulqudus Abubakre

Thanks a lot

Collapse
 
codefinity profile image
Manav Misra

🤔 I 🤔 using TEMPLATE 🏷 can alleviate some of this too.