JAVASCRIPT
Dynamically Add and Remove DOM Elements
Learn how to programmatically create new HTML elements from scratch, append them to the DOM, and efficiently remove existing elements using pure JavaScript.
const container = document.getElementById('container');
// Create a new div element
const newElement = document.createElement('div');
newElement.textContent = 'I am a new element!';
newElement.classList.add('dynamic-item');
// Append the new element to the container
container.appendChild(newElement);
// To remove an element (e.g., the new one after some time)
// Assuming 'newElement' is still in scope and attached
// newElement.remove();
// Or remove a specific existing element by its ID
const itemToRemove = document.getElementById('item-to-be-removed');
if (itemToRemove) {
itemToRemove.remove();
}
How it works: This snippet demonstrates the fundamental process of dynamically manipulating the DOM. `document.createElement()` is used to create a new HTML element in memory. `element.textContent` sets its plain text content, and `element.classList.add()` manages its CSS classes. The new element is then added to an existing parent element using `parentNode.appendChild()`. To remove an element, the `element.remove()` method is called directly on the element you wish to delete from the DOM.