The document.createElement Function in JavaScript

Apr 15, 2022

The createElement() function in JavaScript is used to programatically add elements to the DOM. It has one required argument, the type of element to create, like 'div' or 'img'. For example, the button below creates and appends a new <div> element.

Below is the HTML and JavaScript for the above button.

<div id="append-elements"></div>
<button onclick="addElement()">Click to Add</button>
function addElement() {
  const doc = document.createElement('div');
  doc.innerHTML = 'Hello World';
  const container = document.querySelector('#append-elements');

Recursive createElement()

Once you create an element, you can use methods like appendChild() to create and append more elements.

const parent = document.querySelector('#nested');

// Create one element...
const child = document.createElement('div');
child.innerText = 'I am the parent\'s child';

// Create another element
const grandchild = document.createElement('h1');
grandchild.innerText = 'I am the grandchild';

// Append 2nd element as a child of the 1st elemtn

Below is the output of the above JavaScript.

I am the Parent

Did you find this tutorial useful? Say thanks by starring our repo on GitHub!

More Fundamentals Tutorials