Creating elements with createElement
Learn to create a new HTML element and add it to the page.
Creating a new element
To create a new HTML element in JavaScript, you use the document.createElement method. It takes a tag name and produces a new element of that tag.
const card = document.createElement('div');The element is not yet on the page; it lives in memory. To make it visible, you must add it to an existing element. Tag names are written in lowercase.
Set text on the element
To add text to the element you created, you use the textContent property. It places the text safely; HTML tags appear as text.
const title = document.createElement('h1');
title.textContent = 'Hello';First you create the element, then you set its properties. The same way you can also set other properties like className or id. We will see how to add the element to the page in the next lesson.
Exercise Create a heading element
Define a variable named heading. Create a new heading element with document.createElement('h2') and assign a short text to its textContent property.
Show example solution
const heading = document.createElement('h2');
heading.textContent = 'Daily';
Test yourself
-
Which creates a new <p> element?
// A const a = document.querySelector('p'); // B const b = document.createElement('p'); // C const c = document.getElementById('p'); // D const d = document.createTextNode('p');- A
- B
- C
- D
Show answer
B — Correct! createElement('p') makes a new <p> element.
-
Create a new li element
const item = document.____('li');Show answer
const item = document.createElement('li'); -
Match methods to their meanings
- document.createElement('span')
- Makes a new span element
- element.textContent = '...'
- Sets the element's text
- document.querySelector('span')
- Selects the first span