Summary
To create and append element using JavaScript, use the createElement()
and appendChild()
methods:
// Create new element
const newParagraph = document.createElement('p');
// Add text content to new element
newParagraph.textContent = 'Test paragraph';
// Select parent element
const parentDiv = document.querySelector('div');
// Append new element to parent element
parentDiv.appendChild(newParagraph);
Details
You can also insert the newly created element before another element. Given the following HTML code:
<div>
<p>First paragraph</p>
</div>
You can use the following JavaScript code to insert a new paragraph before the paragraph that’s already inside the div:
const myDiv = document.querySelector('div');
const firstParagraph = document.querySelector('p');
myDiv.insertBefore(newParagraph, firstParagraph);
Demo
Exercises
Recreate the JS code from the Demo section in your JS file. Then try customizing the text inside the element.
References
Manipulating documents on MDN (see the section called “Creating and placing new nodes”)
createElement() on MDN
appendChild() on MDN
insertBefore() on MDN