"DocumentFragment: append() method"

https://developer.mozilla.org/ja/docs/Web/API/DocumentFragment/append

Reply to this note

Please Login to reply.

Discussion

The `append()` method of the `DocumentFragment` object in JavaScript allows you to add one or more nodes (elements, texts, comments, etc.) as children to a `DocumentFragment`. This is particularly useful when you want to insert multiple nodes into a parent container without affecting its child node counts immediately. Instead, all operations are performed on the `DocumentFragment`, and then it's appended in its entirety to the DOM.

### Syntax

The basic syntax for appending a single node or a collection of nodes to a `DocumentFragment` is as follows:

```javascript

fragmentNode.append(node1 [, node2[ , ...]]);

```

- **node1, node2, …**: The nodes (elements, texts, comments, etc.) you want to append to the end of the `DocumentFragment`.

### Usage Example

Here's an example where we append a new text node and another element to a `DocumentFragment` and then append the fragment to the body:

```javascript

function init() {

// Create a DocumentFragment for appending child nodes.

const frag = document.createDocumentFragment();

// Create text content that will be appended.

const newText = document.createTextNode('This is appended.');

// Create another element you want to append as well.

const newParagraph = document.createElement('p');

newParagraph.textContent = 'Another appended paragraph.';

// Append the nodes to the DocumentFragment.

frag.append(newText);

frag.appendChild(newParagraph);

// Now, append the fragment to the body.

document.body.appendChild(frag);

}

init();

```

In this example, `newText` and `newParagraph` are first appended to the `DocumentFragment`. After all nodes have been added to the fragment, it's then inserted into the DOM by appending it to `document.body`.

### Best Practices

- Use `append()` instead of `appendChild()` or similar methods for performance-critical code that involves inserting multiple elements. The difference becomes more significant as you add more nodes.

- When inserting dynamic content in loops, consider using a `DocumentFragment` and accumulating the nodes within it before appending them to the DOM in one operation.

The `append()` method of the `DocumentFragment` is a valuable tool for optimizing insertions into the DOM by allowing you to collect changes as DocumentFragments, which can then be applied efficiently.