Difference Between document.createElement()
and document.createDocumentFragment()
in JavaScript
1. document.createElement()
This method creates a single HTML element.
Contents
Syntax:
javascriptCopyEditconst element = document.createElement('div');
Key Points:
- Creates a single element node (e.g.,
<div>
,<p>
, etc.). - Appends directly to the DOM if needed.
- Suitable when creating a single element.
Example:
javascriptCopyEditconst div = document.createElement('div');
div.textContent = 'Hello!';
document.body.appendChild(div);
2. document.createDocumentFragment()
This method creates a lightweight container to hold multiple elements without adding extra nodes to the DOM.
Syntax:
javascriptCopyEditconst fragment = document.createDocumentFragment();
Key Points:
- A temporary container for holding multiple elements.
- Does not represent any element in the DOM.
- Used for performance reasons when appending multiple elements to the DOM in one go.
- Improves performance as it minimizes reflows and repaints.
Example:
javascriptCopyEditconst fragment = document.createDocumentFragment();
for (let i = 0; i < 5; i++) {
const p = document.createElement('p');
p.textContent = `Paragraph ${i + 1}`;
fragment.appendChild(p);
}
document.body.appendChild(fragment); // Appends all paragraphs at once
Key Differences Summary:
Feature | document.createElement() | document.createDocumentFragment() |
---|---|---|
Purpose | Creates a single element. | Creates a temporary container for multiple elements. |
Representation in DOM | Represents an actual element in the DOM. | Does not represent any visual node in the DOM. |
Performance | Slower when adding multiple elements (triggers reflows for each). | Faster for batch additions (appends all at once). |
Use Case | When creating a single element like <div> or <p> . | When creating and appending multiple elements efficiently. |
DOM Reflows | Triggers a reflow for each append. | Minimizes reflows by appending everything at once. |
When to Use Which?
Use
createElement()
→ When you need a single element. Use
createDocumentFragment()
→ When you need to append many elements at once for better performance.
Final Tip:
- When you append a
DocumentFragment
to the DOM, its children are moved to the DOM, and the fragment itself disappears. - This is why fragments are used as a performance optimization tool.
So, if you’re adding many elements, use DocumentFragment
for better performance.