The document.createElement Function in JavaScript

How to Filter an Object by Key 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');

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

const grandchild = document.createElement('h1');
grandchild.innerText = 'I am the grandchild';


Below is the output of the above JavaScript.

More Fundamentals Tutorials

Source link

Leave a reply

Please enter your comment!
Please enter your name here