Creating Elements with createElement
What you'll learn: How to programmatically create new HTML elements using JavaScript that you can add to your page dynamically.
The Core Idea
Until now, you've learned how to select existing elements from the DOM. But what if you need to add brand new elements that weren't in your original HTML? That's where document.createElement() comes in. This method lets you build HTML elements on the fly using JavaScript.
Think of it like a factory: document.createElement() manufactures a fresh, blank element of whatever type you specify, ready to be customized and placed into your document.
How createElement Works
The basic syntax is straightforward:
const newDiv = document.createElement('div');
This creates a new <div> element in memory. Important: it's not yet visible on the page—it exists only in JavaScript until you explicitly add it to the DOM.
The Basic Workflow
- Create the element with
createElement - Customize it (add content, attributes, classes)
- Insert it into the DOM (covered in upcoming lessons)
Here's a simple example showing creation and customization:
// Create a new paragraph element
const newParagraph = document.createElement('p');
// It's now an element node in memory, ready to be configured
// (We'll learn how to add it to the page in the next lessons)
You can create any valid HTML element by passing its tag name as a string: 'div', 'span', 'section', 'button', 'img', etc.
Key Takeaway: document.createElement() manufactures new DOM elements in memory—they won't appear on the page until you insert them into the DOM tree.