JavaScript: Create / Insert HTML Element

, , …,

This page shows you how to use JavaScript to create/insert 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");
 newNode.appendChild(document.createTextNode("hello"));

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

Like what you read? Buy JavaScript in Depth. Thanks.