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');
container.appendChild(doc);
}
Recursive createElement()
Once you create an element, you can use methods like appendChild()
to create and append more elements.
const parent = document.querySelector('#nested');
const child = document.createElement('div');
child.innerText = 'I am the parent\'s child';
const grandchild = document.createElement('h1');
grandchild.innerText = 'I am the grandchild';
parent.appendChild(child);
child.appendChild(grandchild);
Below is the output of the above JavaScript.