JS: 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 = evt.target; // 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. JS: Change CSS
  2. JS: Change Element's Content
  3. JS: Create HTML Element
  4. JS: Remove HTML Element

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