Create A DOM Element - JavaScript Tutorial

Skip to content

Home » Create a DOM Element

This tutorial shows you how to create a DOM element and attach it to the DOM tree.

To create a DOM element, you use the createElement() method.

const element = document.createElement(htmlTag);Code language: JavaScript (javascript)

The following example creates a new <div> element:

const e = document.createElement('div');Code language: JavaScript (javascript)

And fill the <div> element with any HTML content:

e.innerHTML = 'JavaScript DOM';Code language: JavaScript (javascript)

And attach the <div> element to the DOM tree by using the appendChild() method:

document.body.appendChild(e);Code language: CSS (css)

Besides using the innerHTML property, you can use the DOM methods to create text nodes and append the text nodes to the new element:

var textnode = document.createTextNode('JavaScript DOM'); e.appendChild(textnode); Code language: JavaScript (javascript)

After that, you can use the appendChild() method to attach the new element to the DOM tree.

Send Cancel Get the Closest Element by SelectorPreviouslyGet the Closest Element by Selector Up NextReplace a DOM Element Replace a DOM Element Search for:

Getting Started

JavaScript Fundamentals

JavaScript Operators

Control Flow

JavaScript Functions

JavaScript Objects

Classes

Advanced Functions

Promises & Async/Await

JavaScript Modules

Javascript Error Handling

JavaScript Runtime

Primitive Wrapper Types

More JavaScript Operators

Tag » Add Dom Element Js