In this tutorial, we aim to teach you how to create and remove DOM (Document Object Model) elements dynamically using JavaScript. This ability to manipulate the DOM is a crucial aspect of creating interactive web applications.
By the end of this tutorial, you will have learned:
Prerequisites: Basic knowledge of HTML, CSS, and JavaScript would be helpful but not necessary.
The DOM is a tree-like structure that represents all the elements of a webpage. JavaScript can interact with the DOM, allowing us to create, modify, delete or add content to a webpage dynamically.
To create a new element in the DOM, we use the document.createElement(element)
method. This creates a new element of the type specified.
Once an element is created, it will not appear on the webpage until it is added to the DOM. This can be done using methods such as appendChild()
or insertBefore()
.
To remove an element from the DOM, we use removeChild()
or remove()
. The removeChild()
method removes a child node from the DOM, while remove()
removes the element itself.
// Create a new paragraph element
let para = document.createElement("p");
// Add some text to the paragraph
para.innerHTML = "This is a new paragraph.";
// Add the new paragraph to the body of the document
document.body.appendChild(para);
In this example, we first create a new paragraph element, then assign some text to it. Finally, we append this paragraph to the body of the document.
// Get the first paragraph in the document
let para = document.querySelector("p");
// Remove the paragraph from the document
para.remove();
Here, we're selecting the first paragraph element in the document and then removing it.
In this tutorial, we've learned how to create and remove DOM elements. We've learned that to see a newly created element, it must be added to the DOM. We also learned that an element can be removed from the DOM.
To continue learning about DOM manipulation, you can explore how to modify DOM elements, such as changing their content or attributes. The Mozilla Developer Network (MDN) is a great resource for learning more about the DOM.
Create and add a new div
element with the text "Hello, World!" to the end of the body.
let div = document.createElement("div");
div.innerHTML = "Hello, World!";
document.body.appendChild(div);
Find the first div
element in the document and remove it.
let div = document.querySelector("div");
div.remove();
Create a new h1
element, add the text "Hello, DOM!" to it, and add it as the first child of the body.
let h1 = document.createElement("h1");
h1.innerHTML = "Hello, DOM!";
document.body.insertBefore(h1, document.body.firstChild);
Keep practicing these exercises and try to create and delete various types of elements to get comfortable with DOM manipulation.