Suggest an editImprove this articleRefine the answer for “How do you create an element in the DOM?”. Your changes go to moderation before they’re published.Approval requiredContentWhat you’re changing🇺🇸EN🇺🇦UAPreviewTitle (EN)Short answer (EN)To create an element in the DOM, you use the **`document.createElement()`** method: it creates a new element that can then be added to the page. **Key point:** creation happens in three steps - create the element, configure it (text, attributes, classes), and add it to the document via `appendChild()`, `prepend()`, `insertBefore()`, `after()`, or `before()`.Shown above the full answer for quick recall.Answer (EN)ImageTo **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 body ``` The 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 list ``` --- ### Summary Creating an element in the DOM consists of three steps: 1. `document.createElement('tag')`: create the element. 2. Configure it (add text, attributes, classes, and so on). 3. Add it to the document via `appendChild()`, `prepend()`, `insertBefore()`, `after()`, or `before()`.For the reviewerNote to the moderator (optional)Visible only to the moderator. Helps review go faster.