JavaScript Create Element – Part 1

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


	<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()" />
		<div id="msg"> </div>

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

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


	function createEle () {
		var sm = document.getElementById('subMain');
		var sMsg = document.getElementById('msg');
		if(sm) {
			sm.innerHTML +=	"";
			var getTag = document.getElementById('textBox').value;
			if (getTag != '')
				var addNewTag = document.createElement(getTag);
				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:


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:


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');

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!


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s