Adding and Removing Elements Dynamically
Creating new elements or removing existing ones is a powerful feature of JavaScript, allowing you to update the structure of the page based on user interactions.
Creating Elements:
You can create new elements with document.createElement(). Once created, these elements are not part of the DOM until you append them using appendChild() or append().
1. append()
The append() method can insert multiple nodes (elements) or text strings to a specified parent node. If you try to add multiple elements, they’ll all be appended as children. Additionally, append() accepts both text and DOM nodes.
- Syntax: parent.append(child1, child2, …, childN)
- Returns: undefined
- Use case: Adding multiple nodes or text content.
Example:
// Select the parent element
const parentElement = document.getElementById("parentDiv");
// Create new elements
const childElement1 = document.createElement("div");
childElement1.textContent = "This is the first child.";
const childElement2 = document.createElement("div");
childElement2.textContent = "This is the second child.";
// Use append to add both elements and text
parentElement.append(childElement1, childElement2, "Some text content");
2. appendChild()
The appendChild() method only accepts a single node and appends it to the specified parent node. Unlike append(), it does not accept text strings, only DOM nodes. If you try to add text, you’ll get an error.
- Syntax: parent.appendChild(child)
- Returns: The appended child node
- Use case: Adding a single node.
Example:
// Select the parent element
const parentElement = document.getElementById("parentDiv");
// Create a new element
const childElement = document.createElement("div");
childElement.textContent = "This is a child added with appendChild.";
// Use appendChild to add the single node
parentElement.appendChild(childElement);
Key Differences b/w append() and appendChild():
- Multiple elements: append() can take multiple elements or text, while appendChild() only takes one node.
- Text strings: append() allows text strings directly, but appendChild() does not.
- Return value: append() returns undefined, whereas appendChild() returns the appended node.
Removing Elements:
To remove elements from the DOM, use the remove() method. Alternatively, you can use removeChild() on a parent element.
Example:
let elementToRemove = document.getElementById("main-title");
elementToRemove.remove(); // Direct removal of the element