DOM: Create/Insert HTML Element

By Xah Lee. Date: . Last updated: .

This page shows you how to use JavaScript to create an HTML element and insert it into a page.

Press the following button to see a paragraph element inserted.

Here's the HTML code:

<button id="id66669">Click Me</button>

Here's the JavaScript code:

const ff = ((event) => {

 // create node
 const newNode = document.createElement("p");
 newNode.appendChild(document.createTextNode("hello"));

 // target node
 const targ = event.target; // the HTML element of the event

 // insert after
 targ.insertAdjacentElement("afterend", newNode);

});

document.getElementById("id66669").addEventListener("click", ff , false);

[see DOM: .insertAdjacentElement]

Create HTML Element

First, you create a element, by

document.createElement

Insert Element

then, insert it, by one of:

[see DOM: Basic DOM Methods]

[see DOM: .insertAdjacentElement]

Using InnerHTML to Create and Insert Nodes

Another way to create and insert nodes is by using InnerHTML. See:

DOM: Difference Between textContent, innerHTML, innerText, nodeValue

Basic DOM How-To

  1. DOM: Basic DOM Methods
  2. Get Elements by ID, Tag, Name, Class, CSS Selector
  3. Change CSS
  4. Change Node Content
  5. Create/Insert Node
  6. Remove Node
  7. Get Element's Attribute Value
  8. Set Element's Attribute Value
  9. List/Add/Remove Class Attribute
  10. Add/Remove Event Handler
  11. DOM: Navigate DOM Tree
Liket it? Put $5 at patreon.

Or, Buy JavaScript in Depth

Patreon me $5. Ask me question on patreon