How do you create an element in the DOM?
To create an element in the DOM, you use the document.createElement() method.
It creates a new element that you can later add to the page.
Example 1: a simple element
javascript
const div = document.createElement('div'); // create a <div> element
div.textContent = 'Hello, world!'; // add text
document.body.appendChild(div); // insert it at the end of bodyThe resulting HTML:
javascript
<body>
<div>Hello, world!</div>
</body>Example 2: with attributes and classes
javascript
const button = document.createElement('button');
button.textContent = 'Click me';
button.className = 'btn-primary';
button.id = 'myButton';
document.body.appendChild(button);Example 3: nested elements
javascript
const card = document.createElement('div');
card.classList.add('card');
const title = document.createElement('h2');
title.textContent = 'Card';
const desc = document.createElement('p');
desc.textContent = 'This is an example of a dynamically created block.';
card.appendChild(title);
card.appendChild(desc);
document.body.appendChild(card);Example 4: adding at a specific spot
If you need to insert an element not at the end, but, for example, before or after another element:
javascript
const newItem = document.createElement('li');
newItem.textContent = 'New item';
const list = document.querySelector('ul');
list.insertBefore(newItem, list.firstChild); // insert at the start of the listSummary
Creating an element in the DOM consists of three steps:
document.createElement('tag'): create the element.- Configure it (add text, attributes, classes, and so on).
- Add it to the document via
appendChild(),prepend(),insertBefore(),after(), orbefore().
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.