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="button69908" type="button">Click Me</button>

Here's the JavaScript code:

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

const ff = (() => {
 const newNode = document. createElement("p");
 newNode.appendChild(document. createTextNode("hello"));
 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:

node.appendChild(new_node)

[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

Buy JavaScript in Depth

JavaScript in Depth

JS Obj Ref

DOM


DOM

Overview

Basic Examples

HTML Input

Web Scripting Examples

Web Scripting Misc

jQuery

node.js