Adding/Removing Elements
Explore how to dynamically manage HTML elements in web pages using JavaScript DOM manipulation. Learn to create new elements, append them to the document, and remove existing ones. This lesson helps you build interactive features by programmatically controlling page content.
We'll cover the following...
document.createElement(element)
You can create a new element using document.createElement(), with the argument element, which is the element name.
Pause and think. Our AI mentor is here to assist!
Given the code above, why is there no output?
Element.appendChild(element_node)
You can use the Element.appendChild(element_node) to attach one element node to another element node as a child.
For instance, we can append h1 as a child element of the <div> element.
Now the newly created <h1> element shows up in the output since we have added it as a child element of the content <div> container.
Element.removeChild(element_node)
You can also use Element.removeChild() to remove a child from a parent element within the HTML document. The function will return the removed element.
Exercise
Create an unordered list with at least three list items using only JavaScript. The unordered list should show up in the HTML document and output correctly.