JavaScript: Create 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:

function f1 (evt) {

 // create node
 var newNode = document.createElement("p");

 // reference node
 var refNode =; // the HTML element of the event

 // insert after
 refNode.parentNode.insertBefore(newNode, refNode.nextSibling);

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

Note: insertBefore method inserts node as children.

nodeA.insertBefore(new_node, ref_node) → insert new_node as a child of nodeA, at a position before ref_node. So, ref_node must be a child of nodeA.

Simple DOM Examples

  1. JavaScript: Change CSS
  2. JavaScript: Change Element's Content
  3. JavaScript: Create HTML Element
  4. JavaScript: Remove HTML Element

  1. JavaScript: document.write
  2. JavaScript: Image Rollover
  3. JavaScript: Pop-up New Window
  4. JavaScript: Digital Clock
  5. JavaScript: Stopwatch
  6. JavaScript: Fade a Element
  7. JavaScript: Fade a Element Using CSS Transition
  8. JavaScript UI: Shake Element
  9. JavaScript: How to Create Tooltip
  10. JavaScript: Falling Snow Effect
  11. JavaScript Floating Box Following Scroll
Like what you read? Buy JavaScript in Depth
or, buy something from my keyboard store