4

The document.createElement Function in JavaScript

 3 years ago
source link: https://masteringjs.io/tutorials/fundamentals/create-element
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

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');
  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');

// 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
parent.appendChild(child);
child.appendChild(grandchild);

Below is the output of the above JavaScript.

I am the Parent
I am the parent's child

I am the grandchild


More Fundamentals Tutorials


Recommend

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK