86. Inserting Elements into the DOM
After creating a new element, we need methods to place it in relation to an existing parent element.
Setup
Assume we have an element reference to the parent: const parent = document.querySelector('#container');
1. appendChild()
Inserts the new element as the last child of the parent element.
javascript const child = document.createElement('p'); child.textContent = 'I am last.';
parent.appendChild(child); //
I am last.
2. prepend() (Modern Method)
Inserts the new element as the first child of the parent element.
javascript const childFirst = document.createElement('h2'); childFirst.textContent = 'I am first.';
parent.prepend(childFirst); //
I am first.
... existing children ...3. insertAdjacentElement() (Advanced Positioning)
This method allows precise control over placement (before or after the element itself, or as the first/last child). We'll use this for detailed layout control.