The modern DOM API provides intuitive methods: **append()** adds content to end (accepts strings and nodes), **prepend()** to beginning, **before()**/**after()** relative to a sibling, **replaceWith()** replaces the element, and **remove()** deletes itself. These are much cleaner than the old `appendChild`/`insertBefore`/`removeChild` pattern.
1Understanding DOM Modification Methods
The modern DOM API provides intuitive methods: append() adds content to end (accepts strings and nodes), prepend() to beginning, before()/after() relative to a sibling, replaceWith() replaces the element, and remove() deletes itself. These are much cleaner than the old appendChild/insertBefore/removeChild pattern.
Use document.createDocumentFragment() to batch-insert many elements. Fragment keeps them in memory until you do one DOM operation.
// Modern DOM modification
const list = document.querySelector('ul');
const newItem = document.createElement('li');
newItem.textContent = 'New Item';
list.append(newItem); // to end
list.prepend('First item'); // to beginning (string!)
newItem.before(document.createElement('li')); // sibling
newItem.remove(); // self-remove2Practical Example
Here is a real-world application of DOM Modification Methods showing how it is used in production JavaScript code.
// DocumentFragment for batch insert
const fragment = document.createDocumentFragment();
for (let i = 0; i < 1000; i++) {
const li = document.createElement('li');
li.textContent = `Item ${i}`;
fragment.append(li);
}
list.append(fragment); // ONE DOM operation for all 10003Best Practices
Follow these guidelines when working with DOM Modification Methods:
1. Use modern methods: append, remove, replaceWith, before, after
2. Use DocumentFragment for batch insertions
3. Clone elements with cloneNode(true) for deep copies
Tip: Use document.createDocumentFragment() to batch-insert many elements. Fragment keeps them in memory until you do one DOM operation.
// Modern DOM modification
const list = document.querySelector('ul');
const newItem = document.createElement('li');
newItem.textContent = 'New Item';
list.append(newItem); // to end
list.prepend('First item'); // to beginning (string!)
newItem.before(document.createElement('li')); // sibling
newItem.remove(); // self-remove