Skip to main content

Building the page with JavaScript

So far you’ve modified existing elements. But often you need to create new ones — render a list of users from an API, add a notification, or build a table from data. This is where document.createElement() comes in.

document.createElement()

Create a new element, configure it, then add it to the page:
The element doesn’t appear on the page until you add it to the DOM with appendChild or similar methods.

A more complete example

This produces:

Adding elements to the page

Several methods for inserting elements, each with a different position:
append() and prepend() are the modern alternatives. They also accept strings: parent.append("Hello") adds a text node. appendChild only accepts elements.

Removing elements

Rendering a list from data

This is the most common use case — take data (from an API, for example) and build the DOM:

With innerHTML (simpler for complex HTML)

innerHTML with template literals is convenient but vulnerable to XSS if the data contains user input. For data from your own API, it’s fine. For user-generated content, use createElement + textContent.

Document fragments (batch insertions)

When adding many elements, each appendChild triggers a page repaint. Use a DocumentFragment to batch insertions:
For small lists (under 100 items), the performance difference is negligible. Use fragments when rendering large datasets or when you notice visible flickering during rendering.

How React replaces this

Everything in this lesson — createElement, appendChild, innerHTML — is what React automates. Compare:
React handles creating, updating, and removing DOM elements for you. You describe what the UI should look like; React figures out how to make it happen.
Understanding createElement helps you appreciate what React does under the hood. You won’t use manual DOM creation in React projects, but you’ll understand error messages and debugging better.

What’s next?

You can create and add elements to the page. Now let’s make them interactive — responding to clicks, typing, and other user actions.

Event listeners

Respond to user interactions like clicks and keyboard input