JS 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.

Example

Press the following button to see a paragraph element inserted.

Code

<button id="button_jmGmR" type="button">Click Me</button>
const button_jmGmR = document.getElementById("button_jmGmR");

const f_do = () => {
 const newNode = document.createElement("p");
 newNode.appendChild(document.createTextNode("hello"));
 button_jmGmR.insertAdjacentElement("afterend", newNode);
};

button_jmGmR.addEventListener("click", f_do);