Creating Elements
Learn how JavaScript can create new HTML elements dynamically and add them to a web page using the DOM.
What is Creating Elements?
JavaScript allows us to create new HTML elements dynamically using the DOM.
The document.createElement() method creates a new HTML element that can later be added to the web page.
Simple Definition
Creating Elements means creating a new HTML element using JavaScript instead of writing that element directly in the HTML document.
The most commonly used method is document.createElement().
JavaScript can create new HTML elements dynamically and add them to the DOM.
How Creating Elements Works
Creating an element normally follows three simple steps: create the element, add content, and attach the element to the document.
Create → Configure → Add the new element to the DOM.
Steps to Create an Element
Create Element
Use document.createElement() to create a new HTML element.
Add Content
Use properties such as textContent to add content.
Add to DOM
Use appendChild() to add the new element to the page.
Example 1: Create a Paragraph
The following browser-side JavaScript creates a new paragraph element and adds text to it.
const paragraph = document.createElement("p");
paragraph.textContent =
"Welcome to CIIT Training Institute";
document.body.appendChild(paragraph);
Output: Welcome to CIIT Training Institute
Example 2: Create a Heading
We can create different HTML elements by passing the required tag name to createElement().
const heading = document.createElement("h2");
heading.textContent = "Learn JavaScript with CIIT";
document.body.appendChild(heading);
Output: Learn JavaScript with CIIT
Example 3: Create a Button
JavaScript can also create interactive elements such as buttons.
const button = document.createElement("button");
button.textContent = "Click Me";
document.body.appendChild(button);
Output: Click Me
Example 4: Create Multiple Elements
Multiple elements can be created and added to the page using JavaScript.
const heading = document.createElement("h2");
heading.textContent = "CIIT Training Institute";
const paragraph = document.createElement("p");
paragraph.textContent = "Learn Full Stack Development";
document.body.appendChild(heading);
document.body.appendChild(paragraph);
Output: p → Learn Full Stack Development
Important Note
document.createElement() creates the element, but it does not automatically place the element on the page.
To add the created element to the page, methods such as appendChild() can be used.
Summary
JavaScript can dynamically create HTML elements using the DOM. The document.createElement() method creates a new element, properties such as textContent add content, and appendChild() adds the element to the document.