JavaScript Create Element – Part 1

This is a simple tutorial helps you start with how to create html elements dynamically using createElement functionality.

XHTML Code

	<h1>JavaScript Create Element</h1>
	<h2>All the tags created dynamically will be added to "subMain" div.</h2>
	<div id="main">
		<form action="#" id="cEleForm" method="post">
			<label><strong>Enter a Tag:</strong><em>(Example:a, p, div, span...)</em></label>
			<input type="text" id="textBox" />
			<input type="button" value="Create" onclick="createEle()" />
			<input type="button" value="Clear Status" onclick="clrSts()" />
		</form>
		<div id="msg"> </div>
	</div>

	<div id="subMain"> </div>

Below is the JavaScript that uses document.createElement functionality to create html elements dynamically:

JavaScript

	function createEle () {
		var sm = document.getElementById('subMain');
		var sMsg = document.getElementById('msg');
		clrSts();
		if(sm) {
			sm.innerHTML +=	"";
			var getTag = document.getElementById('textBox').value;
			if (getTag != '')
			{
				var addNewTag = document.createElement(getTag);
				sm.appendChild(addNewTag);
				sMsg.innerHTML += "Status: "+getTag+" tag added Successfully!... Please check view source."; document.getElementById('textBox').value = ""; } else {alert ("Please enter a tag");} } }

Here is a bit of explanation on how this works:

Prerequisites: You should already be familiar with XHTML before reading further.

The JavaScript createElement and appendChild are the key functions which helps us to create html elements dynamically.

Let’s examine the below code:

document.createElement('p')

The createElement function takes html tag as parameter and creates the tag dynamically. Once the element is created it have to be added to the DOM to access it using appendChild function. Have a look at the below code:

sourceNode.appendChild()

The below example shows how to create a tag dynamically and add it to the “subMain” div.

var sm = document.getElementById('subMain');
var addNewTag = document.createElement('p');
sm.appendChild(addNewTag);

Few things to consider carefully: All the elements which are added dynamically will always be added at the end(In my example the p tag will be added as the last tag in div subMain). Withiout appendChild you will not be able to see the tag anywhere. The dynamically created tags are always empty.

Click here to download the complete code.

Good Luck!