JavaScript: Create / Insert HTML Element

, , …,

This page is a JavaScript tutorial on creating & inserting HTML element.

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.

Like what you read? Please tell friends, share link, or Buy JavaScript in Depth. Thanks.
blog comments powered by Disqus