Efficiently Append Multiple Elements


Appending multiple elements to the DOM can be inefficient if done individually.

Use a document fragment to batch append operations.

const fragment = document.createDocumentFragment();
const container = document.getElementById('container');

for (let i = 0; i < 5; i++) {
    const newElement = document.createElement('div');
    newElement.textContent = `Item ${i + 1}`;
    fragment.appendChild(newElement);
}

container.appendChild(fragment);

/*
  This can be useful specially when dynamically you have to append content on web page.
*/

A Document Fragment is a lightweight container used to hold and manipulate a set of DOM elements before appending them to the main document.

It improves performance by minimizing the work the browser has to do when updating the webpage layout and appearance, which helps make page updates faster and smoother.

You Might Also Like

Remove Multiple DOM Elements

Use a loop to detach elements and then remove them all at once. ``` const elementsToRemove = docum...

Inject a Script into Document Head or Body Tags

You can inject js script into the document head dynamically like this : ``` const basicScript = do...