JavaScript: Create & Insert HTML Element

, , …,
Want to master JavaScript in a week? Buy Xah JavaScript Tutorial.

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");
 newNode.appendChild(document.createTextNode("♥"));

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

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

blog comments powered by Disqus