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 is the HTML code:

<button id="button69908" type="button">Click Me</button>

Here is the JavaScript code:

const button69908 = document.getElementById("button69908");

const ff = (() => {
 const newNode = document.createElement("p");
 button69908. insertAdjacentElement("afterend", newNode);

button69908 . addEventListener ("click", ff , false);

[see DOM: insertAdjacentElement]

Create HTML Element

const newNode = document.createElement("p");

Insert Element

Best is to use:

node.insertAdjacentElement(position, new_node)

[see DOM: insertAdjacentElement]

Other ways:


[see DOM: .appendChild]

p_node.insertBefore(new_node, node_x)

Inserts new_node as child of p_node before node_x.

[see DOM: Basic DOM Methods]

Using InnerHTML to Create/Insert Nodes

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

DOM: Difference Between textContent, innerHTML, innerText, nodeValue

JavaScript in Depth

DOM Scripting Tutorial


Basic Examples

HTML Input

Web Scripting Examples

Web Scripting Misc