Introduction
Manipulating the DOM involves not just updating styles and text but also dynamically creating and removing elements to build interactive and responsive web applications. In this guide, you’ll learn how to:
- Create new DOM elements.
- Insert elements into the appropriate location in the DOM.
- Remove elements from the DOM.
Creating and Inserting New Elements
To create and insert new elements, you can use the document.createElement() and appendChild() methods.
Example 1: Adding a New Element
HTML:
Creating Elements
JavaScript (example.js):
const addElement = () => {
// Create a new h1 element
const newElement = document.createElement("h1");
// Assign text content to the element
newElement.innerText = "Jell-O, Burled!";
// Append the element to the body of the document
document.body.appendChild(newElement);
};
// Execute the function when the page loads
window.onload = addElement;
When you load this page, the text "Jell-O, Burled!" will appear as an <h1> in the body of the document.
Example 2: Using innerHTML for Multiple Elements
const addElementAlt = () => {
document.body.innerHTML = "Jell-O, Burled!
";
};
window.onload = addElementAlt;
Note: While innerHTML can be efficient for adding multiple elements, remember that it parses the string as HTML. Use it carefully to avoid overwriting or injecting unintended elements.
Removing Elements
Removing elements is simpler. Use the remove() method on a selected element to delete it from the DOM.
Example: Removing an Element
HTML:
Removing Elements
Div 1
Div 2
Div 3
JavaScript (example.js):
const removeSecondDiv = () => {
const secondDiv = document.getElementById("2");
secondDiv.remove();
};
window.onload = removeSecondDiv;
When you load this page, the second <div> ("Div 2") will be removed from the DOM.
Key Takeaways
In this guide, you learned how to:
- Create new elements using
document.createElement(). - Insert elements into the DOM using
appendChild(). - Remove elements from the DOM using
remove().
These techniques are foundational for building dynamic and interactive web applications.